You need to sign in to do that
Don't have an account?
How to cover execute method in test class for Batch class.
Hi guys.
I have batch calss name:Del_leads
and a Schedule Class bulkdelleads.
When i am writing test method for batch class it is not covering the execute method i am calling this execute from schedule class.Can any body help to figure out the problem.
Batch Class:-
=====================
global class Del_leads implements Database.Batchable<sobject>
{
public String query;
public date d=System.today();
public integer i=7;
Public Date z=d-i;
Public String s;
public integer j;
Public string k='Name'+','+'Company'+','+'phone'+','+'Email';
global Database.QueryLocator start(Database.BatchableContext BC){
system.debug(query);
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC,List<Lead> Lds){
for( j=0;j<lds.size();j++){
if(j==0){
s +=k+'\n'+ lds[j].Name+','+lds[j].Company+','+lds[j].phone+','+lds[j].Email;
} else{
s +=+'\n'+ lds[j].Name+','+lds[j].Company+','+lds[j].phone+','+lds[j].Email;
}
}
Blob b=Blob.valueOf(s);
Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
efa.setFileName('attachment.csv');
efa.setBody(b);
Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
mail.setToAddresses(new String[] {'franktoanil@gmail.com'});
mail.setSenderDisplayName('Batch Processing');
mail.setSubject('Batch Process Completed');
mail.setPlainTextBody('Please find the attachment of deleted records');
mail.setFileAttachments(new Messaging.EmailFileAttachment[] {efa});
Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
delete Lds;
}
global void finish(Database.BatchableContext BC){
System.debug(LoggingLevel.WARN,'Deleting Leads Finished');
}
=====================================================
/*-----------------Test Method-----------------Only 47 % test coverage*/
=====================================================
public static testMethod void Del_leads (){
List <Lead> lds = new List<Lead>();
for(integer i = 0; i<200; i++){
Lead l = new Lead(LastName='Anil',Company='ef');
lds.add(l);
}
insert lds;
test.startTest();
Del_leads dl = new Del_Leads();
dl.query='select id,Name,Company,Phone,Email from lead where createddate<=:z and date_opened__c=null ';
ID batchprocessid = Database.executeBatch(dl);
test.stoptest();
System.AssertEquals(
database.countquery('SELECT COUNT()'+' FROM Lead '),200);
}
}
============================
Schedule Class
============================
global class bulkdelleads Implements Schedulable{
public static String CRON_EXP = '0 0 0 3 9 ? 2022';
global void Execute(SchedulableContext SC){
Del_leads ld=new Del_leads();
ld.query='select id,Name,Company,Phone,Email from lead where createddate<=:z and date_opened__c=null ';
database.executebatch(ld);
}
==================================
/*----------Test Method------------------ 100% test Coverage-*/
==================================
static testmethod void bulkdelleads () {
Test.startTest();
Lead l = new Lead ();
l.LastName = 'Raghu ';
l.company='eg';
insert l;
// Schedule the test job
String jobId = System.schedule('bulkdelleads ',bulkdelleads.CRON_EXP,new bulkdelleads ());
// Get the information from the CronTrigger API object
CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,
NextFireTime
FROM CronTrigger WHERE id = :jobId];
// Verify the expressions are the same
System.assertEquals(bulkdelleads.CRON_EXP,ct.CronExpression);
// Verify the job has not run
System.assertEquals(0, ct.TimesTriggered);
// Verify the next time the job will run
System.assertEquals('2022-09-03 00:00:00',
String.valueOf(ct.NextFireTime));
Test.stopTest();
}
}
Thanks
Anil.B
Hi,
This may not be the best approach but may help you out.
You can call your execute method directly within your test so you could have something like-
Good luck!
Rich.
Hi,
Generally the reason behind the execute method is not calling will be,
When the query you are using is not returning any records.
So please make sure that your query returning records by using some debug logs.
If your query returns some records then the Execute method will defiantly be called, as you wrote test method in proper way.
Hi Richie D,
Thanks for the reply,
I used ur code ,when we are directly calling the execute method .
Then the querylocator and finish method is not getting coverage.
only the execute method is getting coverage.
and system assert also giving error.
Error:-Expected is 0 ,Actual is null.
Thanks
Anil.B
Hi HariDinesh,
Your are correct my code is not returing the query.
I made the corrections now its working fine.
But when iam using System Assert the Same error is coming.
System.AssertException: Assertion Failed: Expected: 0, Actual: 200
If i remove that its showing 100%
----------Test Method----------------------
public static testMethod void Del_leads (){
List <Lead> lds = new List<Lead>();
for(integer i = 0; i<200; i++){
Lead l = new Lead(LastName='Anil',Company='ef');
lds.add(l);
}
insert lds;
test.startTest();
Del_leads dl = new Del_Leads();
dl.query='select id,Name,Company,Phone,Email,date_opened__c from lead Where CreatedDate<=Today AND Date_opened__c=null limit 200 ';
ID batchprocessid = Database.executeBatch(dl,200);
test.stoptest();
System.AssertEquals(database.countquery('SELECT COUNT() FROM Lead '),200);
}
Thanks
Anil.B
Hi,
That is good to hear that problem is solved.
You might need to change the system.assert slightly or leave it for now..
If solution resolves your problem make it as marked so that other might also benefits with the solution.
HI @anilbathula@
If you want to excite wrapper class in test class you have to call to methods as same other methods.
if you resolved your bug. please mark my best answer
Thanks
Suraj Tripati