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
Ashish Kumar YadavAshish Kumar Yadav 

how to cover batch apex class to complete code coverage.

Hi Team,

Can you please help me to code coverage of below code.

Batch Apex
==========

global class  SchemeSendEmail implements Database.Batchable<sObject>,Database.AllowsCallouts,Database.Stateful
{
    public Id samid;
    public String SchemeApplicablefor;
    public String soqlQuery='';
    public SchemeSendEmail(Id SchemeMasterId,String SchemeApplicablefor){
        samid = SchemeMasterId;
        this.SchemeApplicablefor = SchemeApplicablefor;
        
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        System.debug('------------>'+SchemeApplicablefor);
        System.debug('------------>'+samid);
        
        
        Set<String> Ret_RTNames = new Set<String>();
        Set<String> Dist_RTNames = new Set<String>();
        Set<String> Both_RTNames = new Set<String>();
        
        if(SchemeApplicablefor == 'Distributor'){
            System.debug('inside distributer'+Dist_RTNames);
            Dist_RTNames.add('India SND');
            Dist_RTNames.add('Brand W');
            Dist_RTNames.add('H&H Modern Trade Distributor');
            Dist_RTNames.add('H&H Traditional Trade Distributor');
            System.debug('after added record type distributer'+Dist_RTNames);
        }
        if(SchemeApplicablefor == 'Retailer'){
            Ret_RTNames.add('H&H Modern Trade Retailer');
            Ret_RTNames.add('H&H Traditional Trade Retailer');
            Ret_RTNames.add('India SND Retailer');
            Ret_RTNames.add('Brand W Retailer');
            System.debug('after added record type Retailer'+Ret_RTNames);
        }
        if(SchemeApplicablefor == 'Both'){
            Both_RTNames.add('India SND');
            Both_RTNames.add('Brand W');
            Both_RTNames.add('H&H Modern Trade Distributor');
            Both_RTNames.add('H&H Traditional Trade Distributor');
            Both_RTNames.add('H&H Modern Trade Retailer');
            Both_RTNames.add('H&H Traditional Trade Retailer');
            Both_RTNames.add('India SND Retailer');
            Both_RTNames.add('Brand W Retailer');
            System.debug('after added record type both'+Both_RTNames);
        }
        
        System.debug('RTNames@@'+Both_RTNames);
        if(SchemeApplicablefor == 'Retailer'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Ret_RTNames';
        }
        
        else if(SchemeApplicablefor == 'Distributor'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Dist_RTNames';
        }
        
        
        else if(SchemeApplicablefor == 'Both'){
            soqlQuery ='SELECT Id, Name, RecordType.Name FROM Account where Recordtype.Name in : Both_RTNames';
        }
        
        
        if(samid == null){
            soqlQuery = '';
        }
        System.debug('soqlQuery@@@@-------->'+soqlQuery);
        return Database.getQueryLocator(soqlQuery);
    }
    
    global void execute(Database.BatchableContext BC, List<Account> scope){
        System.debug('Scope size ----->'+ scope.size());
        
        Set<id> accIdswithCurrentSM = new Set<id>();
        List<Scheme_Assign_Master__c> AssignToAll = new List<Scheme_Assign_Master__c>();
        
        
        Map<Id,Account> mapAccount = New Map<Id,Account>(scope);
        List<Scheme_Assign_Master__c> SchemeList;
        
        SchemeList=[select Id,Account__c,Retailer_Account__c,Scheme_Master__c from Scheme_Assign_Master__c where Scheme_Master__c =: samid and (Retailer_Account__c in : mapAccount.keySet() OR Account__c in : mapAccount.keySet())];
        System.debug('SchemeList@@'+SchemeList);
       
        for(Scheme_Assign_Master__c samObj :SchemeList){
            if(samObj.Account__c != null){
                accIdswithCurrentSM.add(samObj.Account__c);
            }
            if(samObj.Retailer_Account__c != null){
                accIdswithCurrentSM.add(samObj.Retailer_Account__c);
            }
        }
        System.debug('Scheme Master with id '+samid +' is Already assigned with accounts, count ->'+accIdswithCurrentSM.size());
        for(Account ac : mapAccount.values()){
            if(!accIdswithCurrentSM.contains(ac.Id)){                
               
                //check ac record type for the retailer account and update value in the retailer id accordingly.
               
                if(SchemeApplicablefor == 'Distributor'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                }
                
                else if(SchemeApplicablefor == 'Retailer'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Retailer_Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                }
                
                else if(SchemeApplicablefor == 'Both'){
                    Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
                    objSAM.Account__c = ac.Id;
                    objSAM.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM);
                    Scheme_Assign_Master__c objSAM1 = new Scheme_Assign_Master__c();
                    objSAM1.Retailer_Account__c = ac.Id;
                    objSAM1.Scheme_Master__c = samid;
                    AssignToAll.add(objSAM1);
                }
            }
        }
        
        /* List<Account> retacc=[SELECT Id, Name, RecordType.Name FROM Account where Customer_RetailerAC__c in : mapAccount.keySet()];
        for(Account ac :retacc ){
        if(!accIdswithCurrentSM.contains(ac.Id)){
        Scheme_Assign_Master__c objSAM = new Scheme_Assign_Master__c();
        objSAM.Account__c = ac.Id;
        objSAM.Scheme_Master__c = samid;
        AssignToAll.add(objSAM);
        }
        }
            */
        
        System.debug('Total SAM to be inserted ---->'+AssignToAll.size());
        if(AssignToAll.size() > 0){
            Database.insert(AssignToAll, false);
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        AsyncApexJob a = [Select Id, Status,ExtendedStatus,NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email from AsyncApexJob where Id =:BC.getJobId()];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {a.CreatedBy.Email};
            mail.setToAddresses(toAddresses);
        mail.setSubject('Scheme Assign to All Distributor/Retailer' + a.Status);
        mail.setPlainTextBody('Scheme Assign to All Distributor/Retailer successfully :- ' + a.TotalJobItems +   'with '+ a.NumberOfErrors + ' failures.');
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); 
    }
}
Best Answer chosen by Ashish Kumar Yadav
Suraj Tripathi 47Suraj Tripathi 47
Hi Ashish,

Please check this test class:-
@istest
public class SchemeSendEmail_Test {
    static testmethod void test(){
        String recType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('India SND').getRecordTypeId();
        list<account> accList= new list<account>();
        for(integer i=0;i<10;i++){
            Account acc= new Account();
            acc.Name='India SND';
            acc.RecordTypeId=recType;
            accList.add(acc);
        }
        insert accList;
        
        Scheme_Assign_Master__c sca= new Scheme_Assign_Master__c();
        sca.Account__c=accList[0].Id;
        sca.Scheme_Master__c=accList[0].Id;
        insert sca;
        
        SchemeSendEmail Sc= new SchemeSendEmail(accList[0].id,'Distributor');
        Database.executeBatch(Sc);
    }
    static testmethod void test1(){
        String recType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('India SND Retailer').getRecordTypeId();
        list<account> accList= new list<account>();
        for(integer i=0;i<10;i++){
            Account acc= new Account();
            acc.Name='India SND';
            acc.RecordTypeId=recType;
            accList.add(acc);
        }
        insert accList;
        
        Scheme_Assign_Master__c sca= new Scheme_Assign_Master__c();
        sca.Account__c=accList[0].Id;
        sca.Scheme_Master__c=accList[0].Id;
        insert sca;
     
        SchemeSendEmail Sc= new SchemeSendEmail(accList[0].id,'Retailer');
        Database.executeBatch(Sc);
       
    }
        
    static testmethod void test2(){
        String recType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('India SND Retailer').getRecordTypeId();
        list<account> accList= new list<account>();
        for(integer i=0;i<10;i++){
            Account acc= new Account();
            acc.Name='India SND';
            acc.RecordTypeId=recType;
            accList.add(acc);
        }
        insert accList;
        
        Scheme_Assign_Master__c sca= new Scheme_Assign_Master__c();
        sca.Account__c=accList[0].Id;
        sca.Scheme_Master__c=accList[0].Id;
        insert sca;
     
        SchemeSendEmail Sc= new SchemeSendEmail(accList[0].id,'Both');
        Database.executeBatch(Sc);
    }
}

Please Mark it as Best Answer if it helps.
Thanks

All Answers

ANUTEJANUTEJ (Salesforce Developers) 
HI Ashish,

Since this code provided is huge and requires an understanding of your implementation, it might not be possible to provide exact test class suggestions. However, the below information should help you get started.

The below articles give a good insight into how to begin writing test class and how coverage can be improved

https://salesforce.stackexchange.com/questions/244788/how-do-i-write-an-apex-unit-test
https://salesforce.stackexchange.com/questions/244794/how-do-i-increase-my-code-coverage-or-why-cant-i-cover-these-lines 

Examples:
https://developer.salesforce.com/docs/atlas.en-us.pages.meta/pages/pages_controller_error_handling.htm
 https://salesforce.stackexchange.com/questions/87533/writing-test-class-for-wrapper-class
https://salesforce.stackexchange.com/questions/108850/apex-test-method-for-wrapper-classes

If this information helps, please mark the answer as best. Thank you
Suraj Tripathi 47Suraj Tripathi 47
Hi Ashish,

Please check this test class:-
@istest
public class SchemeSendEmail_Test {
    static testmethod void test(){
        String recType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('India SND').getRecordTypeId();
        list<account> accList= new list<account>();
        for(integer i=0;i<10;i++){
            Account acc= new Account();
            acc.Name='India SND';
            acc.RecordTypeId=recType;
            accList.add(acc);
        }
        insert accList;
        
        Scheme_Assign_Master__c sca= new Scheme_Assign_Master__c();
        sca.Account__c=accList[0].Id;
        sca.Scheme_Master__c=accList[0].Id;
        insert sca;
        
        SchemeSendEmail Sc= new SchemeSendEmail(accList[0].id,'Distributor');
        Database.executeBatch(Sc);
    }
    static testmethod void test1(){
        String recType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('India SND Retailer').getRecordTypeId();
        list<account> accList= new list<account>();
        for(integer i=0;i<10;i++){
            Account acc= new Account();
            acc.Name='India SND';
            acc.RecordTypeId=recType;
            accList.add(acc);
        }
        insert accList;
        
        Scheme_Assign_Master__c sca= new Scheme_Assign_Master__c();
        sca.Account__c=accList[0].Id;
        sca.Scheme_Master__c=accList[0].Id;
        insert sca;
     
        SchemeSendEmail Sc= new SchemeSendEmail(accList[0].id,'Retailer');
        Database.executeBatch(Sc);
       
    }
        
    static testmethod void test2(){
        String recType = Schema.SObjectType.Account.getRecordTypeInfosByName().get('India SND Retailer').getRecordTypeId();
        list<account> accList= new list<account>();
        for(integer i=0;i<10;i++){
            Account acc= new Account();
            acc.Name='India SND';
            acc.RecordTypeId=recType;
            accList.add(acc);
        }
        insert accList;
        
        Scheme_Assign_Master__c sca= new Scheme_Assign_Master__c();
        sca.Account__c=accList[0].Id;
        sca.Scheme_Master__c=accList[0].Id;
        insert sca;
     
        SchemeSendEmail Sc= new SchemeSendEmail(accList[0].id,'Both');
        Database.executeBatch(Sc);
    }
}

Please Mark it as Best Answer if it helps.
Thanks
This was selected as the best answer
Ashish Kumar YadavAshish Kumar Yadav
Hi Suraj Tripathi 47,

I mark as a best answer because of you are almost close.I make the changes and its work.

Thanks for your such efforts.