You need to sign in to do that
Don't have an account?
Saddam Hussain 33
Batch apex Execute method not covering in Test class
Hi,
Below is the batch apex and Test class.
global class DeleteCaseData implements Database.Batchable<SObject>, Database.Stateful{
global Map<Id, String> errorMap {get; set;}
global Map<Id, SObject> IdToSObjectMap {get; set;}
global DeleteCaseData(){
errorMap = new Map<Id, String>();
IdToSObjectMap = new Map<Id, SObject>();
}
global Database.QueryLocator start(Database.BatchableContext BC) {
String clsDat = Date.today().addmonths(120).adddays(1).format(); //Date.today().adddays(1).format();
system.debug('----clsdat----'+clsDat);
String query = 'Select Id, status,Category__c,Origin From Case where status = \'Closed\'';
if(clsDat != null){
query = query + ' AND ' + '( X18_Months__c =: clsDat OR X120_Months__c = :clsDat) ';
system.debug('----query-1----'+query); //X18_Months__c =: clsDat OR
}
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<SObject> scope) {
List<Case> CaseList = new List<Case>();
for(SObject s : scope){
Case cs = (Case) s;
//cs.Status = 'New';
CaseList.add(cs);
}
if(CaseList.size() > 0) {
List<Database.DeleteResult> casdele = Database.delete(CaseList, false);
Integer index = 0;
for(Database.DeleteResult dsr : casdele){
if(!dsr.isSuccess()){
String errMsg = dsr.getErrors()[0].getMessage();
errorMap.put(CaseList[index].Id, errMsg);
IdToSObjectMap.put(CaseList[index].Id, CaseList[index]);
}
index++;
}
}
}
global void finish(Database.BatchableContext BC) {
//Send an email to the User after your batch completes
if(!errorMap.isEmpty()){
string myid = 'ecsfdc.in@capgemini.com';
//List<User> usrs = [Select id,email from user where profile.name = 'System Administrator'];
AsyncApexJob a = [SELECT id, ApexClassId,JobItemsProcessed, TotalJobItems,NumberOfErrors, CreatedBy.Email FROM AsyncApexJob WHERE id = :BC.getJobId()];
String body = 'Hi,\n \n' + 'The batch job ' + 'DeleteCaseData ' + 'has finished. \n' + 'There were ' + errorMap.size() + ' errors. Please find the error list attached. \n \n Thanks,';
// Creating the CSV file
String finalstr = 'Id, CaseNumber, Error \n';
String subject = 'Case - Apex Batch Error List';
String attName = 'Delete Case Errors.csv';
for(Id id : errorMap.keySet()){
string err = errorMap.get(id);
Case Cse = (Case) IdToSObjectMap.get(id);
string recordString = '"'+id+'","'+Cse.CaseNumber+'","'+err+'"\n';
finalstr = finalstr +recordString;
}
// Define the email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Create the email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(attName);
efa.setBody(Blob.valueOf(finalstr));
// Sets the paramaters of the email
email.setSubject( subject );
email.setToAddresses( new String[] {myid} );
email.setPlainTextBody( body );
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
}
Test Class:
@isTest
public class DeleteCaseData_Test {
Public static testMethod void myUnitTest() {
Account ac = new Account();
ac.Name = 'Test';
ac.Customer_Serno__c = '123';
insert ac;
Contact con = new Contact();
con.LastName = 'Testing';
con.SSN__c='353535353535';
con.SerNo__c='4353077';
insert con;
Product_Custom__c pd = new Product_Custom__c();
pd.Name = 'Test';
pd.Pserno__c = '1542';
insert pd;
Financial_Account__c fa = new Financial_Account__c();
fa.Product__c = pd.id;
fa.Account_Serno__c = '1200';
fa.Account_Number__c = '125646456';
fa.Customer__c = ac.Id;
fa.Customer_Serno__c = '126464';
fa.Product_Serno__c = '454564';
insert fa;
Card__c cd = new Card__c();
cd.Card_Number_Truncated__c = '353453******5345';
cd.Product__c = pd.Id;
cd.People_Serno__c = '12456465';
cd.Card_Serno__c = '45785415';
cd.Prod_Serno__c='4746565';
cd.People__c = con.Id;
cd.Financial_Account__c =fa.Id;
cd.Financial_Account_Serno__c = '784966';
insert cd;
List<Case> cslist = new List<Case>();
Case cs = new Case();//(Status='New',Origin = 'Email', Category__c='None');
cs.AccountId = ac.Id;
cs.Financial_Account__c = fa.Id;
cs.ContactId = con.Id;
cs.Origin = 'email';
cs.Status='Closed';
cs.Card__c = cd.Id;
cs.X120_Months__c = '2028-03-28';
cs.X18_Months__c ='2019-03-28';
cs.Category__c = 'None';
cslist.add(cs);
Insert cslist;
Test.StartTest();
DeleteCaseData casedelete = new DeleteCaseData();
ID batchprocessid = Database.executeBatch(casedelete);
Test.StopTest();
}
}
Below is the batch apex and Test class.
global class DeleteCaseData implements Database.Batchable<SObject>, Database.Stateful{
global Map<Id, String> errorMap {get; set;}
global Map<Id, SObject> IdToSObjectMap {get; set;}
global DeleteCaseData(){
errorMap = new Map<Id, String>();
IdToSObjectMap = new Map<Id, SObject>();
}
global Database.QueryLocator start(Database.BatchableContext BC) {
String clsDat = Date.today().addmonths(120).adddays(1).format(); //Date.today().adddays(1).format();
system.debug('----clsdat----'+clsDat);
String query = 'Select Id, status,Category__c,Origin From Case where status = \'Closed\'';
if(clsDat != null){
query = query + ' AND ' + '( X18_Months__c =: clsDat OR X120_Months__c = :clsDat) ';
system.debug('----query-1----'+query); //X18_Months__c =: clsDat OR
}
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<SObject> scope) {
List<Case> CaseList = new List<Case>();
for(SObject s : scope){
Case cs = (Case) s;
//cs.Status = 'New';
CaseList.add(cs);
}
if(CaseList.size() > 0) {
List<Database.DeleteResult> casdele = Database.delete(CaseList, false);
Integer index = 0;
for(Database.DeleteResult dsr : casdele){
if(!dsr.isSuccess()){
String errMsg = dsr.getErrors()[0].getMessage();
errorMap.put(CaseList[index].Id, errMsg);
IdToSObjectMap.put(CaseList[index].Id, CaseList[index]);
}
index++;
}
}
}
global void finish(Database.BatchableContext BC) {
//Send an email to the User after your batch completes
if(!errorMap.isEmpty()){
string myid = 'ecsfdc.in@capgemini.com';
//List<User> usrs = [Select id,email from user where profile.name = 'System Administrator'];
AsyncApexJob a = [SELECT id, ApexClassId,JobItemsProcessed, TotalJobItems,NumberOfErrors, CreatedBy.Email FROM AsyncApexJob WHERE id = :BC.getJobId()];
String body = 'Hi,\n \n' + 'The batch job ' + 'DeleteCaseData ' + 'has finished. \n' + 'There were ' + errorMap.size() + ' errors. Please find the error list attached. \n \n Thanks,';
// Creating the CSV file
String finalstr = 'Id, CaseNumber, Error \n';
String subject = 'Case - Apex Batch Error List';
String attName = 'Delete Case Errors.csv';
for(Id id : errorMap.keySet()){
string err = errorMap.get(id);
Case Cse = (Case) IdToSObjectMap.get(id);
string recordString = '"'+id+'","'+Cse.CaseNumber+'","'+err+'"\n';
finalstr = finalstr +recordString;
}
// Define the email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Create the email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(attName);
efa.setBody(Blob.valueOf(finalstr));
// Sets the paramaters of the email
email.setSubject( subject );
email.setToAddresses( new String[] {myid} );
email.setPlainTextBody( body );
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
}
Test Class:
@isTest
public class DeleteCaseData_Test {
Public static testMethod void myUnitTest() {
Account ac = new Account();
ac.Name = 'Test';
ac.Customer_Serno__c = '123';
insert ac;
Contact con = new Contact();
con.LastName = 'Testing';
con.SSN__c='353535353535';
con.SerNo__c='4353077';
insert con;
Product_Custom__c pd = new Product_Custom__c();
pd.Name = 'Test';
pd.Pserno__c = '1542';
insert pd;
Financial_Account__c fa = new Financial_Account__c();
fa.Product__c = pd.id;
fa.Account_Serno__c = '1200';
fa.Account_Number__c = '125646456';
fa.Customer__c = ac.Id;
fa.Customer_Serno__c = '126464';
fa.Product_Serno__c = '454564';
insert fa;
Card__c cd = new Card__c();
cd.Card_Number_Truncated__c = '353453******5345';
cd.Product__c = pd.Id;
cd.People_Serno__c = '12456465';
cd.Card_Serno__c = '45785415';
cd.Prod_Serno__c='4746565';
cd.People__c = con.Id;
cd.Financial_Account__c =fa.Id;
cd.Financial_Account_Serno__c = '784966';
insert cd;
List<Case> cslist = new List<Case>();
Case cs = new Case();//(Status='New',Origin = 'Email', Category__c='None');
cs.AccountId = ac.Id;
cs.Financial_Account__c = fa.Id;
cs.ContactId = con.Id;
cs.Origin = 'email';
cs.Status='Closed';
cs.Card__c = cd.Id;
cs.X120_Months__c = '2028-03-28';
cs.X18_Months__c ='2019-03-28';
cs.Category__c = 'None';
cslist.add(cs);
Insert cslist;
Test.StartTest();
DeleteCaseData casedelete = new DeleteCaseData();
ID batchprocessid = Database.executeBatch(casedelete);
Test.StopTest();
}
}
The below lines are not coverd.
global void execute(Database.BatchableContext BC, List<SObject> scope) {
List<Case> CaseList = new List<Case>();
for(SObject s : scope){
Case cs = (Case) s;
//cs.Status = 'New';
CaseList.add(cs);
}
if(CaseList.size() > 0) {
List<Database.DeleteResult> casdele = Database.delete(CaseList, false);
Integer index = 0;
for(Database.DeleteResult dsr : casdele){
if(!dsr.isSuccess()){
String errMsg = dsr.getErrors()[0].getMessage();
errorMap.put(CaseList[index].Id, errMsg);
IdToSObjectMap.put(CaseList[index].Id, CaseList[index]);
}
index++;
}
}
}
global void finish(Database.BatchableContext BC) {
//Send an email to the User after your batch completes
if(!errorMap.isEmpty()){
string myid = 'ecsfdc.in@capgemini.com';
//List<User> usrs = [Select id,email from user where profile.name = 'System Administrator'];
AsyncApexJob a = [SELECT id, ApexClassId,JobItemsProcessed, TotalJobItems,NumberOfErrors, CreatedBy.Email FROM AsyncApexJob WHERE id = :BC.getJobId()];
String body = 'Hi,\n \n' + 'The batch job ' + 'DeleteCaseData ' + 'has finished. \n' + 'There were ' + errorMap.size() + ' errors. Please find the error list attached. \n \n Thanks,';
// Creating the CSV file
String finalstr = 'Id, CaseNumber, Error \n';
String subject = 'Case - Apex Batch Error List';
String attName = 'Delete Case Errors.csv';
for(Id id : errorMap.keySet()){
string err = errorMap.get(id);
Case Cse = (Case) IdToSObjectMap.get(id);
string recordString = '"'+id+'","'+Cse.CaseNumber+'","'+err+'"\n';
finalstr = finalstr +recordString;
}
// Define the email
Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
// Create the email attachment
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName(attName);
efa.setBody(Blob.valueOf(finalstr));
// Sets the paramaters of the email
email.setSubject( subject );
email.setToAddresses( new String[] {myid} );
email.setPlainTextBody( body );
email.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
// Sends the email
Messaging.SendEmailResult [] r = Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
}
}
}
http://www.infallibletechie.com/2013/09/test-class-for-batch-apex-in-salesforce.html
Thanks,
Anil