0

how to write test class for batch class ? this covers only 44%

global Class Batchsample implements Database.Batchable<sObject>{
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator([
            select id from Attendance__c 
            where Login_Date__c = LAST_MONTH AND 
                Leave_Type__c not in ('SL','EL','AL','Half Day')
        ]);
    }
    global void execute(Database.BatchableContext BC,list<Attendance__c> scope){
        delete scope;
    }
    global void finish(Database.BatchableContext BC){
    }
}

test class

@isTest
public class  batchsampleTest
{
    static testMethod void test1()
     {
         
             list<Attendance__c> sample = new list<Attendance__c>();
             
                 for(Integer i = 0; i< 100; i++){
                     Attendance__c att = new Attendance__c(Login_Time__c= Date.Today()-30,Project__c = 'AHM',Leave_Type__c = 'SL');
                     
                                        
                     sample.add(att);

                 }
         
         
         insert sample;
 Test.startTest();
     
     
          batchsample bs = new batchsample();
          DataBase.executebatch(bs);
     
     Test.stopTest();
     
     }
     
  }
  • You Leave Type is SL and which is not expected in query(NOT IN). Give some other value and try. – Ysr Shk Jul 29 '20 at 10:05
  • only the execute and finishmethods are not running – G Naveen Kumar Jul 29 '20 at 10:12
  • Because, your start method is not returning data. Since your query return ZERO records. Add Leave_Type__c (any other than than those 4 values given in batch) – Ysr Shk Jul 29 '20 at 10:17
  • still the same, should i use delete sample? – G Naveen Kumar Jul 29 '20 at 10:22
0

Naveen, you need to create test data which fulfills your query in Start(). As per the query , you are fetching attendance records which have login date in last month AND Leave_Type__c Not equal to (!=) any of the values 'SL','EL','AL','Half Day'.

For your test records in Test class method, you are creating records with Login Time in last month and Leave type = 'SL'. so it does not fulfill the query filter conditions.

I assume, your batch class is running fine. When u run the test class(and test method), and execute the batch in withing Test.StartTest() and Test.StopTest(), it should automatically delete your test record(in test class execution transaction). So you don't need to write any test code to delete.

You should assert the results (which means u should query the test record with all filter conditions and it should return zero records.).

Not the answer you're looking for? Browse other questions tagged or ask your own question.