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
sanjdevsanjdev 

Help required to create test class for apex batch class Urgent

global class ClsTargetedCalls implements Database.Batchable<sObject>
{      
    global final String Query;      
    global String curRBDMonth = '';
    ClsUtilRBD clsRBD = new ClsUtilRBD(); 
    
    global Map<String,List<Store_Visit__c>> map_StoreIdAndStoreVisit = new Map<String,List<Store_Visit__c>>();
    global Set<Store_Visit__c> set_StoreVisitsToUpdate = new Set<Store_Visit__c>();
    global List<Store_Visit__c> list_plannedCalls = new List<Store_Visit__c>();
    global List<Store_Visit__c> list_storeVisitsFromMap = new List<Store_Visit__c>();    
    global List<Store_Visit__c> list_StoreVisitsToUpdate = new List<Store_Visit__c>();
    
    
    //Class constructor
    global ClsTargetedCalls()
    {   system.debug('hi'+clsRBD.getMonth(system.today()));       
        curRBDMonth = clsRBD.getMonth(system.today());
        system.debug('curRBDMonth$$$$$ : '+curRBDMonth);
        Query = 'select Id, OwnerId,Contact__c, Start_Time__c,Targeted_Actual__c, Owner.UserRole.Name, Visit_Date__c, Planned__c,RBD_Month__c, recordType.Name, Store__c, Status__c, Objective_1_Achieved__c, Objective_1_Comments__c, Objective_2_Achieved__c, Objective_2_Comments__c, Objective_3_Achieved__c, Objective_3_Comments__c, DW_Sell__c, DW_Stock__c, MF_Sell__c, MF_Stock__c, MF_Trial_Lens__c, NC_Sell__c, NC_Stock__c, NC_Trial_Lens__c, OP_38_Sell__c, OP_38_Stock__c, PV_A_Sell__c, PV_A_Stock__c, PV_A_Trial_Lens__c, PV_Sell__c, PV_Stock__c, PV_Trial_Lens__c, ReNu_Sell__c, ReNu_Stock__c, SDD_Sell__c, SDD_Stock__c, SDD_Trial_Lens__c, SDD_A_Sell__c, SDD_A_Stock__c, SDD_A_Trial_Lens__c, SL_59_Sell__c, SL_59_Stock__c,  SL_T_Sell__c, SL_T_Stock__c, Is_ReNu_In_Clinic_Sample_available__c, SL38_Medallist_Stock__c, SL38_Medalist_Sell__c, SL38_Medalist_Trial_Lens__c, PV_MF_Sell__c, PV_MF_Stock__c,  PV_MF_Trial_Lens__c,Optima_Easy_Sell__c,Optima_Easy_Stock__c,re_nu_Sensitive_Sell__c,re_nu_Sensitive_Stock__c,Biotrue_Sell__c,Biotrue_Stock__c,SL59_Medalist_II_Trial_Lens__c,SL_66_T_Medalist_66_Toric_Trial_Lens__c,Is_Biotrue_inclinic_sample_available__c,re_nu_Sensitive_Inclinic_Sample__c from Store_Visit__c where RBD_Month__c = : curRBDMonth order by Store__c'; 
    }
    
    //Start Method
    global Database.QueryLocator start(Database.BatchableContext BC)
    {          
        system.debug('query>>>>>'+query);
        return Database.getQueryLocator(query);
    }
    
    //Execute Method
    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
        Boolean isCompleted = false;
        system.debug('list_StoreVisit>>>>'+scope);
        for(sObject sObj : scope)
        {
            Store_Visit__c objSV = (Store_Visit__c)sObj;
            
            if(map_StoreIdAndStoreVisit.get(objSV.Store__c) == null)
                map_StoreIdAndStoreVisit.put(objSV.Store__c,new List<Store_Visit__c>());
            map_StoreIdAndStoreVisit.get(objSV.Store__c).add(objSV);
            system.debug('map_StoreIdAndStoreVisit>>>>>'+map_StoreIdAndStoreVisit);
        }
   
        //Iterate over the map's keyset to get the list of planned calls for every store
        for(String storeID : map_StoreIdAndStoreVisit.keyset())
        {
            system.debug('Main FOR - MAp keyset iteration');
            list_storeVisitsFromMap=new List<Store_Visit__c>();
            list_plannedCalls= new List<Store_Visit__c>();
            list_storeVisitsFromMap.addAll(map_StoreIdAndStoreVisit.get(storeID));
            for(Integer i=0;i<list_storeVisitsFromMap.size();i++)
            {
                system.debug('Store Record>>>>>>>: '+storeID);
                system.debug('SV Record>>>>>>>: '+list_storeVisitsFromMap[i]);
                //Populate the list of Planned calls for the current store and current RBD month
                if(list_storeVisitsFromMap[i].Planned__c == true)
                    list_plannedCalls.add(list_storeVisitsFromMap[i]);
                system.debug('list_plannedCalls>>>>>'+list_plannedCalls);
                system.debug('list_plannedCalls size>>>>>'+list_plannedCalls.size());
                /*if(i==(map_StoreIdAndStoreVisit.get(storeID).size())-1)
                {
                    system.debug('Planned calls list size equal to store visits list size');
                    isCompleted = true;
                    break;
                }*/
            }
            system.debug('masterlist'+list_storeVisitsFromMap.size());
            system.debug('sublist'+list_plannedCalls.size());
            if(list_storeVisitsFromMap.size()==list_plannedCalls.size())
            {
                system.debug('Store visits lesser than the planned calls');
                for(Store_Visit__c tempSV1 : list_storeVisitsFromMap)
                {
                    if(tempSV1.Status__c == 'Completed')
                    {
                        tempSV1.Targeted_Actual__c = true;
                        set_StoreVisitsToUpdate.add(tempSV1);
                        system.debug('tempSV1.Targeted_Actual__c>>>>'+tempSV1.Targeted_Actual__c);
                        system.debug('tempSV1.Status__c>>>>'+tempSV1.Status__c);
                    }
                }                   
            }
            else if(list_storeVisitsFromMap.size()>list_plannedCalls.size())
            {
                system.debug('Store visits greater than the planned calls');
                Integer completed_count=0;
                for(Integer j=0;j<list_storeVisitsFromMap.size();j++)
                {
                    if(completed_count==(list_plannedCalls.size()))
                        break;
                    else
                    {
                    
                        system.debug('Greater - Status Completed'+list_storeVisitsFromMap[j].Visit_Date__c+list_storeVisitsFromMap[j].Status__c+'planned'+list_storeVisitsFromMap[j].Planned__c);
                        if(list_storeVisitsFromMap[j].Status__c == 'Completed' )
                        {   completed_count++;
                            list_storeVisitsFromMap[j].Targeted_Actual__c = true;
                            system.debug('list_storeVisitsFromMap[j].Targeted_Actual__c>>>>'+list_storeVisitsFromMap[j].Targeted_Actual__c);
                            system.debug('list_storeVisitsFromMap[j].Status__c>>>>'+list_storeVisitsFromMap[j].Status__c);
                            set_StoreVisitsToUpdate.add(list_storeVisitsFromMap[j]);
                        }
                    }
                        
                }
            }
        }
        list_StoreVisitsToUpdate.addAll(set_StoreVisitsToUpdate);
        system.debug('set_StoreVisitsToUpdate>>>>>'+set_StoreVisitsToUpdate);
        system.debug('list_StoreVisitsToUpdate>>>>>'+list_StoreVisitsToUpdate);
        if(list_StoreVisitsToUpdate.size()>0)
            update list_StoreVisitsToUpdate;
    }
    
    //Finish Method
    global void finish(Database.BatchableContext BC)
    {

    }
}

Best Answer chosen by Admin (Salesforce Developers) 
sanjdevsanjdev

Hi Suree,

 

Thanks for your suggestion, i can able to achieve 91% and below is the code snippet.

 

@isTest
private class ClsTargetedCalls_Test{
public static testMethod void testBatch() {

        UserRole objRoleSalesAdmin = [Select Id From UserRole where name = 'INDVC Sales Administrator']; 
        UserRole objRoleSalesRep = [Select Id From UserRole where name = 'JPNVC Sales Executive (Fukuoka)']; 
        
        Profile objProfileIntegrationUser = [SELECT Id FROM profile WHERE name='APAVC Integration User']; 
        Profile objProfileSalesAdmin = [SELECT Id FROM profile WHERE name='APAVC System Administrator']; 
        Profile objProfileSalesRep = [SELECT Id FROM profile WHERE name='APAVC JP Sales Executive']; 
        
        User objUserIngetration = new User(alias = 'integra', email='integration@testorg.com', emailencodingkey='UTF-8',
                             lastname='Testing', languagelocalekey='en_US', localesidkey='en_US', timezonesidkey='America/Los_Angeles',
                             username='integration@testorg.com', profileid = objProfileIntegrationUser.Id);
        
        User objUserSalesAdmin = new User(alias = 'salesadm', email='salesadmin@testorg.com', emailencodingkey='UTF-8',
                         lastname='Testing', languagelocalekey='en_US', localesidkey='en_US', timezonesidkey='America/Los_Angeles',
                         username='salesadmin@testorg.com', profileid = objProfileSalesAdmin.Id, userRoleId=objRoleSalesAdmin.Id);

        User objUserSalesRep = new User(alias = 'salesrep', email='salesrep@testorg.com', emailencodingkey='UTF-8',
                         lastname='Testing', languagelocalekey='en_US', localesidkey='en_US', timezonesidkey='America/Los_Angeles',
                         username='salesrep@testorg.com', profileid = objProfileSalesRep.Id, userRoleId=objRoleSalesRep.Id);

        List<User> list_User = new List<User>();
        list_User.add(objUserIngetration);
        list_User.add(objUserSalesAdmin);
        list_User.add(objUserSalesRep);
        insert list_User;

        // Getting Id for recordType APAVC Direct, APAVC Indirect  
        Id idDirectRecordType = [SELECT Id FROM RecordType 
                                        WHERE Name = 'APAVC Direct' AND SObjectType='Account'].Id;
        Id idIndirectRecordType = [SELECT Id FROM RecordType 
                                        WHERE Name = 'APAVC Indirect' AND SObjectType='Account'].Id;

        Account objDirectAccount = new Account(Name = 'Test APAVC Direct Account', RecordTypeId = idDirectRecordType, OwnerId = objUserSalesRep.Id);
        Account objIndirectAccount = new Account(Name = 'Test APAVC Indirect Account', RecordTypeId = idIndirectRecordType);
        System.runAs(objUserIngetration) {
            List<Account> list_Account = new List<Account>();
            list_Account.add(objDirectAccount);
            insert list_Account;
       
          }
            System.runAs(objUserSalesAdmin) {
            insert objIndirectAccount;
            
            List<Account_Profile__c> list_AccountProfile = new List<Account_Profile__c>();
            
            Id idRecordTypeRetailer = [SELECT Id FROM RecordType 
                                        WHERE Name = 'APAVC Retailer' AND SObjectType='Account_Profile__c'].Id;
            Account_Profile__c oAccountProfile = new Account_Profile__c();
            oAccountProfile.Account__c = objIndirectAccount.Id;
            oAccountProfile.OwnerId = objUserSalesRep.Id;
            oAccountProfile.recordTypeId = idRecordTypeRetailer;
            list_AccountProfile.add(oAccountProfile);

            oAccountProfile = new Account_Profile__c();
            oAccountProfile.Account__c = objDirectAccount.Id;
            oAccountProfile.OwnerId = objUserSalesRep.Id;
            oAccountProfile.recordTypeId = idRecordTypeRetailer;
            list_AccountProfile.add(oAccountProfile);
            insert list_AccountProfile;

            Id idRecordTypeAPAVC = [SELECT Id FROM RecordType 
                                        WHERE Name = 'APAVC' AND SObjectType='Contact'].Id;
            Contact oContact = new Contact();
            oContact.AccountId = objDirectAccount.Id;
            oContact.FirstName = 'Test';
            oContact.LastName = 'Contact';
            insert oContact;
            }
            System.runAs(objUserSalesRep) {
            Id idRecordTypeSalesVisit = [Select Id From RecordType Where Name = 'APAVC Unplanned Sales' and SObjectType='Store_Visit__c'].Id;
            
            Store_Visit__c objStoreVisit = new Store_Visit__c(Visit_Date__c = System.today(), Store__c = objDirectAccount.Id, RecordTypeId = idRecordTypeSalesVisit, Status__c = 'Open');
            Store_Visit__c objStoreVisitFuture = new Store_Visit__c(Visit_Date__c = System.today()+1, Store__c = objDirectAccount.Id, RecordTypeId = idRecordTypeSalesVisit, Status__c = 'Open');
            
            List<Store_Visit__c> list_StoreVisit = new List<Store_Visit__c>();
            list_StoreVisit.add(objStoreVisit);
            list_StoreVisit.add(objStoreVisitFuture);
            insert list_StoreVisit;
            
            Store_Visit__c objStoreVisit1 = new Store_Visit__c();
            objStoreVisit1.Status__c = 'Completed';
            objStoreVisit1.Objective_1_Achieved__c = true;
            objStoreVisit1.Objective_2_Achieved__c = true;
            objStoreVisit1.Objective_3_Achieved__c = true;
            objStoreVisit1.Planned__c = true;
            insert objStoreVisit1;
            
            Store_Visit__c objStoreVisitEdit = [Select Id, Status__c,Planned__c, Objective_1_Achieved__c, Objective_2_Achieved__c, Objective_3_Achieved__c, Start_Time__c, End_Time__c,Enter_Time__c from Store_Visit__c where Id=:objStoreVisit1.Id];
            
            objStoreVisitEdit.Status__c = 'Completed';
            objStoreVisitEdit.Objective_1_Achieved__c = true;
            objStoreVisitEdit.Objective_2_Achieved__c = true;
            objStoreVisitEdit.Objective_3_Achieved__c = true;
            objStoreVisitEdit.Planned__c = true;
            objStoreVisitEdit.Start_Time__c = System.now().addMinutes(-10);
            objStoreVisitEdit.End_Time__c = System.now(); 
            list_StoreVisit.add(objStoreVisitEdit);
            update list_StoreVisit;
            
            Test.StartTest();
            ClsTargetedCalls targetCall = new ClsTargetedCalls();            
            
            //List<sObject> scope = new List<sObject>();
           
            Database.BatchableContext BC;
            targetCall.start(BC);
            targetCall.execute(BC,list_StoreVisit);
            targetCall.finish(BC);            
            Test.StopTest();
          }
}
}

All Answers

Suresh RaghuramSuresh Raghuram

first create an instance of a class and call the methods in your batch class through the instance, second thing find the inputs whihc you are giving for the batch class and give hard coded values in the testclass, then perform insert update ,insert delete, or only insert.

sanjdevsanjdev

Hi Suree,

 

Thanks for your suggestion, i can able to achieve 91% and below is the code snippet.

 

@isTest
private class ClsTargetedCalls_Test{
public static testMethod void testBatch() {

        UserRole objRoleSalesAdmin = [Select Id From UserRole where name = 'INDVC Sales Administrator']; 
        UserRole objRoleSalesRep = [Select Id From UserRole where name = 'JPNVC Sales Executive (Fukuoka)']; 
        
        Profile objProfileIntegrationUser = [SELECT Id FROM profile WHERE name='APAVC Integration User']; 
        Profile objProfileSalesAdmin = [SELECT Id FROM profile WHERE name='APAVC System Administrator']; 
        Profile objProfileSalesRep = [SELECT Id FROM profile WHERE name='APAVC JP Sales Executive']; 
        
        User objUserIngetration = new User(alias = 'integra', email='integration@testorg.com', emailencodingkey='UTF-8',
                             lastname='Testing', languagelocalekey='en_US', localesidkey='en_US', timezonesidkey='America/Los_Angeles',
                             username='integration@testorg.com', profileid = objProfileIntegrationUser.Id);
        
        User objUserSalesAdmin = new User(alias = 'salesadm', email='salesadmin@testorg.com', emailencodingkey='UTF-8',
                         lastname='Testing', languagelocalekey='en_US', localesidkey='en_US', timezonesidkey='America/Los_Angeles',
                         username='salesadmin@testorg.com', profileid = objProfileSalesAdmin.Id, userRoleId=objRoleSalesAdmin.Id);

        User objUserSalesRep = new User(alias = 'salesrep', email='salesrep@testorg.com', emailencodingkey='UTF-8',
                         lastname='Testing', languagelocalekey='en_US', localesidkey='en_US', timezonesidkey='America/Los_Angeles',
                         username='salesrep@testorg.com', profileid = objProfileSalesRep.Id, userRoleId=objRoleSalesRep.Id);

        List<User> list_User = new List<User>();
        list_User.add(objUserIngetration);
        list_User.add(objUserSalesAdmin);
        list_User.add(objUserSalesRep);
        insert list_User;

        // Getting Id for recordType APAVC Direct, APAVC Indirect  
        Id idDirectRecordType = [SELECT Id FROM RecordType 
                                        WHERE Name = 'APAVC Direct' AND SObjectType='Account'].Id;
        Id idIndirectRecordType = [SELECT Id FROM RecordType 
                                        WHERE Name = 'APAVC Indirect' AND SObjectType='Account'].Id;

        Account objDirectAccount = new Account(Name = 'Test APAVC Direct Account', RecordTypeId = idDirectRecordType, OwnerId = objUserSalesRep.Id);
        Account objIndirectAccount = new Account(Name = 'Test APAVC Indirect Account', RecordTypeId = idIndirectRecordType);
        System.runAs(objUserIngetration) {
            List<Account> list_Account = new List<Account>();
            list_Account.add(objDirectAccount);
            insert list_Account;
       
          }
            System.runAs(objUserSalesAdmin) {
            insert objIndirectAccount;
            
            List<Account_Profile__c> list_AccountProfile = new List<Account_Profile__c>();
            
            Id idRecordTypeRetailer = [SELECT Id FROM RecordType 
                                        WHERE Name = 'APAVC Retailer' AND SObjectType='Account_Profile__c'].Id;
            Account_Profile__c oAccountProfile = new Account_Profile__c();
            oAccountProfile.Account__c = objIndirectAccount.Id;
            oAccountProfile.OwnerId = objUserSalesRep.Id;
            oAccountProfile.recordTypeId = idRecordTypeRetailer;
            list_AccountProfile.add(oAccountProfile);

            oAccountProfile = new Account_Profile__c();
            oAccountProfile.Account__c = objDirectAccount.Id;
            oAccountProfile.OwnerId = objUserSalesRep.Id;
            oAccountProfile.recordTypeId = idRecordTypeRetailer;
            list_AccountProfile.add(oAccountProfile);
            insert list_AccountProfile;

            Id idRecordTypeAPAVC = [SELECT Id FROM RecordType 
                                        WHERE Name = 'APAVC' AND SObjectType='Contact'].Id;
            Contact oContact = new Contact();
            oContact.AccountId = objDirectAccount.Id;
            oContact.FirstName = 'Test';
            oContact.LastName = 'Contact';
            insert oContact;
            }
            System.runAs(objUserSalesRep) {
            Id idRecordTypeSalesVisit = [Select Id From RecordType Where Name = 'APAVC Unplanned Sales' and SObjectType='Store_Visit__c'].Id;
            
            Store_Visit__c objStoreVisit = new Store_Visit__c(Visit_Date__c = System.today(), Store__c = objDirectAccount.Id, RecordTypeId = idRecordTypeSalesVisit, Status__c = 'Open');
            Store_Visit__c objStoreVisitFuture = new Store_Visit__c(Visit_Date__c = System.today()+1, Store__c = objDirectAccount.Id, RecordTypeId = idRecordTypeSalesVisit, Status__c = 'Open');
            
            List<Store_Visit__c> list_StoreVisit = new List<Store_Visit__c>();
            list_StoreVisit.add(objStoreVisit);
            list_StoreVisit.add(objStoreVisitFuture);
            insert list_StoreVisit;
            
            Store_Visit__c objStoreVisit1 = new Store_Visit__c();
            objStoreVisit1.Status__c = 'Completed';
            objStoreVisit1.Objective_1_Achieved__c = true;
            objStoreVisit1.Objective_2_Achieved__c = true;
            objStoreVisit1.Objective_3_Achieved__c = true;
            objStoreVisit1.Planned__c = true;
            insert objStoreVisit1;
            
            Store_Visit__c objStoreVisitEdit = [Select Id, Status__c,Planned__c, Objective_1_Achieved__c, Objective_2_Achieved__c, Objective_3_Achieved__c, Start_Time__c, End_Time__c,Enter_Time__c from Store_Visit__c where Id=:objStoreVisit1.Id];
            
            objStoreVisitEdit.Status__c = 'Completed';
            objStoreVisitEdit.Objective_1_Achieved__c = true;
            objStoreVisitEdit.Objective_2_Achieved__c = true;
            objStoreVisitEdit.Objective_3_Achieved__c = true;
            objStoreVisitEdit.Planned__c = true;
            objStoreVisitEdit.Start_Time__c = System.now().addMinutes(-10);
            objStoreVisitEdit.End_Time__c = System.now(); 
            list_StoreVisit.add(objStoreVisitEdit);
            update list_StoreVisit;
            
            Test.StartTest();
            ClsTargetedCalls targetCall = new ClsTargetedCalls();            
            
            //List<sObject> scope = new List<sObject>();
           
            Database.BatchableContext BC;
            targetCall.start(BC);
            targetCall.execute(BC,list_StoreVisit);
            targetCall.finish(BC);            
            Test.StopTest();
          }
}
}

This was selected as the best answer