function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Venkateswarlu PVenkateswarlu P 

Batch Apex Test Class Code Coverage Issue

global class Batch_contact_delete implements Database.Batchable<sobject> {
    global Database.QueryLocator start(Database.BatchableContext bc){
        string query='Select LastName,CreatedDate,AccountId,Account.Id from Contact where CreatedDate=LAST_MONTH';
        return Database.getQueryLocator(query);
    }
    global Void execute(Database.BatchableContext bc,List<contact> conList){
        delete conlist;
    }
    global void finish(Database.BatchableContext bc){
         system.debug('****************Start Finish********************');
    }
}
-------------------
Test Class
--------------------
@isTest
private class Batch_contact_delete_Test_Class {
	@isTest
    static void delConAcc(){
        Account a = new Account();
        a.Name='Raju';
        Insert a;
        Contact c = new contact();
        c.LastName='Ravi';
        c.AccountId=a.id;
        insert c;
        Test.startTest();
        	Batch_contact_delete bd = new Batch_contact_delete();
        	Id JobId = Database.executeBatch(bd,10);
        Test.stopTest();        
        Integer count = [Select count() from Contact where accountId=:a.id];
        System.assertEquals(0, count);
    }
}

I am getting Code covarage as 66% only. Is there any issue with Test class 
Best Answer chosen by Venkateswarlu P
SFDC Dev 2269SFDC Dev 2269
Hey Venkateswarlu P,
Your Start query fetches Contact which were created in last month that is why in your test class no records are retrieved from the query as created date would be today and not last month. So, to test your funtionality and you need to satisfy the condition mentioned in your start query. 
You could use Test.setCreatedDate(c.Id, System.today()-31); in your code after inserting Contact record. This will satisfy your condtion 'WHERE createdDate=LAST_MONTH' and execute the batch.
you could refer below test class:
@isTest
private class Batch_contact_delete_Test_Class {
	@isTest
    static void delConAcc(){
        Account a = new Account();
        a.Name='Raju';
        Insert a;
        Contact c = new contact();
        c.LastName='Ravi';
        c.AccountId=a.id;
        insert c;
        // Set the createdDate to last month i.e. today's date - 31
        Test.setCreatedDate(c.Id, System.today()-31); 
        Test.startTest();
        	Batch_contact_delete bd = new Batch_contact_delete();
        	Id JobId = Database.executeBatch(bd,10);
        Test.stopTest();        
        Integer count = [Select count() from Contact where accountId=:a.id];
        System.assertEquals(0, count);
    }
}
Thanks!