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
Raju Mushke 19Raju Mushke 19 

its urjent basis. i am doing unit testing for batch apex but its not increased.could you please anyone help me how do i improve code coverage for below batch apex.

batch apex class:

public class lar_BatchConvertInterimPromptsToOpp implements Database.Batchable<sObject>,Schedulable,Database.Stateful,Database.AllowsCallouts{
   
    
   //Batch Configuration
    private String interimPromptQuery = 'SELECT  Id,Opportunity__c,End_Date__c,Client__r.RecordType.Name,Prompt__r.Prompt_Id__c,'+
        'Client__r.Customer_Id__c,Closed_Date__c,client__c,Prompt_Status__c,Type__c,Client__r.Customer_Status__c,'+
        'Last_Action_Owner__c,Interim_Action_Date__c,Client__r.Relationship_Manager_BRID__c,Client__r.End_Date__c,'+
        'Client__r.R_Marker__c,Prompt__r.Category__c,Customer_Prompt_ID__c, Prompt__r.Sub_Category__c,'+
        'Prompt__r.Short_Description__c,ActionNotesDesc__c,Last_Action_Owner_User__c '+
        'FROM Customer_Prompt__c ';
    public string queryFilter = '';    
    public bar_BatchService bService;  
    public static Id jobId;
    
    
    public lar_BatchConvertInterimPromptsToOpp() {
        queryFilter = queryFilter;
        
    }
    
    /**
* START BATCH
*/
    public Database.QueryLocator start(Database.BatchableContext BC){
        List<String> listLiveTRMS = new List<String>();
        //Change the Query accrding to JIRA: BUKSFBTWOC-125
        List<Interim_Prompts_Rollout__c> listInterimPromptsRollout = [Select Market__c from Interim_Prompts_Rollout__c where Enabled_for_Interim_Job__c = true Limit 50000];
        for (Interim_Prompts_Rollout__c obj : listInterimPromptsRollout) {
            listLiveTRMS.add(obj.Market__c);
        }

        queryFilter = ' WHERE Last_Action_Owner_User__r.Team_Name__c IN  (\''+String.join(listLiveTRMS, '\',\'')+'\') '+queryFilter ;
        
        String query = '';
        query = interimPromptQuery +''+ queryFilter;
        String emailIds = null;
        lar_Common_Setting__mdt emailSetting = lar_Utility.getSetting(lar_Constant.EMAIL_RECEIVER_BATCH_SETTING);
        if(emailSetting != null){
            emailIds = emailSetting.Value__C;
        }
        bService  = new bar_BatchService('lar_BatchConvertInterimPromptsToOpp','Batch to convert interim prompt', query, emailIds, true);
        return Database.getQueryLocator(query);
    }
    
    /**
* EXECUTE BATCH
*/
    public void execute(Database.BatchableContext BC, List<Customer_Prompt__c> interimPromptList){
        lar_ConvertPromptsToOppHelper.jobId = bc.getJobId();
        lar_ConvertPromptsToOppHelper.bService = bService;
        lar_ConvertPromptsToOppHelper.convertInterimPromptsToOpp(interimPromptList);
    }
    
    
    /*
* EXECUTE Schedular
*/
    public void execute(SchedulableContext sc) {
        
        lar_BatchConvertInterimPromptsToOpp objBatch = new lar_BatchConvertInterimPromptsToOpp();
        objBatch.queryFilter = buildQueryFilter();
        Database.executeBatch(objBatch,lar_Constant.CALLOUT_LIMIT);
    }
    
    /**
* FINISH BATCH
*/
    public void finish(Database.BatchableContext BC){
        bService.finish();
    }
    
    public String buildQueryFilter() {
        queryFilter = '';
        Map<String, Interim_Prompt_Batch_Processing__mdt> settingMap = getInerimProcessingSettings();
        
        if (settingMap.containsKey('premium')) {
            queryFilter = ' AND Internal_Status__c = \''+lar_Constant.INTERIM+'\' AND Interim_Action_Date__c != NULL AND Interim_Action_Date__c > LAST_N_DAYS:30  '+
                'AND End_Date__c = NULL AND Last_Action_Owner_User__c !=NULL AND Last_Action_Owner_User__r.IsActive = true '+
                'AND ( Client__r.Customer_Status__c = \'Active\' AND Client__r.RecordType.Name = \''+lar_Constant.ACC_RC_TYPE_PREMIER_CUSTOMER+'\' )  Order By Client__r.Id';
        } else if(settingMap.containsKey('community')) {
            queryFilter = ' WHERE Prompt__r.Prompt_Id__c = \''+lar_Constant.PROMPTID_1534+'\'';                        
        } else {
            queryFilter = ' WHERE ((Internal_Status__c = \'Interim\' AND Interim_Action_Date__c >= LAST_N_DAYS:30 AND Interim_Action_Date__c != NULL) '+
                ' OR (Prompt__r.Prompt_Id__c = \''+lar_Constant.PROMPTID_1534+'\'))'+ 
                ' AND End_Date__c = NULL Order By Client__r.Id ';
        }

        return queryFilter;
    }
    
    /**
* returns competitor product holding record type to be used for each topic heading
*/
    public static Map<String, Interim_Prompt_Batch_Processing__mdt> getInerimProcessingSettings(){
        Map<String, Interim_Prompt_Batch_Processing__mdt> settingMap = new Map<String, Interim_Prompt_Batch_Processing__mdt>();
        Map<String, Sobject> settings = bar_CustomMetadataUtility.getAll(new Interim_Prompt_Batch_Processing__mdt());
        
        for(Sobject sObj : settings.values()) {
            Interim_Prompt_Batch_Processing__mdt obj = (Interim_Prompt_Batch_Processing__mdt)sObj;
            if (obj.Default__c) {
                settingMap.put(obj.DeveloperName.toLowerCase(), obj);
            }            
        }
        return settingMap;
    }

    
}

 


can anyone please help how to do this.i am very new to the test clases.

 

ShirishaShirisha (Salesforce Developers) 
Hi Raju,

Greetings!

Unfortunately,we can't provide you the exact test class code however,I can provide you the sample test classes for Batch class and best practices which help you to write the test classes on your own.

https://apexcoder.com/2016/11/08/how-to-write-test-class-for-batch-apex-in-salesforce/#:~:text=Batch%20Class%3A&text=In%20below%20code%2C%20we%20are%20testing%20above%20batch%20class%20by,updated%20by%20batch%20apex%20correctly.&text=Note%3A%20%E2%80%93%20As%20best%20practice%2C,StopTest().

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_testing_best_practices.htm

Kindly let me know if it helps you and close your query by marking it as best answer so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
Raju Mushke 19Raju Mushke 19

Hi Shirisha,

i have written below test class for above batch apex.but its cover only 55 %.if you have any idea to improve my code coverage please suggest me.


@isTest
public class lar_BatchConvertInterimPromptsToOppTest {
    
    public static  TestMethod void executeTestConvertInterimPromptsToOpp(){
        Account client = lar_TestClassUtility.createPersonAccount('lastName', '123123123', 'Premier Customer');
        client.Customer_Status__c='Active';
        client.End_Date__c=Date.Today();
        update client;
        /*  Prompt__c prompt = lar_TestClassUtility.createPrompt(lar_Constant.DIGITAL_ADOPTION, 'Channel Migration');
            prompt.Prompt_Id__c = lar_Constant.PROMPTID_1534;
            insert Prompt1; */
        Prompt__c prompt = lar_TestClassUtility.createPromptInstance(lar_Constant.SECURE_BORROWING, 'Residential & BTL','1535');
        prompt.Prompt_Id__c = lar_Constant.PROMPTID_1534;
        insert Prompt;
        
        
        Interim_Prompts_Rollout__c intPRol = new Interim_Prompts_Rollout__c(Market__c = 'Cheshire Market', Enabled_for_Interim_Job__c = true);
        insert intPRol; 
        
        Profile  p = [SELECT Id, Name FROM Profile  WHERE UserLicense.Name = 'Salesforce' LIMIT 1];
        // User without manager
        User u2 = new User(
            alias = 'Justus2', email='info@justuscloud.com', 
            emailencodingkey='UTF-8', lastname='Van den Berg', 
            languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id,
            timezonesidkey='America/Los_Angeles', 
            username='test_class2@justuscloud.com',
            Team_Name__c = 'Cheshire TRMs',
            Market__c = 'Cheshire TRMs',
            //Market__c = 'Birmingham Market',
            EmployeeId__c = 'lakshmi',
            IsActive = true
            
           
        );
        insert u2;
        
        customer_Prompt__c customerPrompt = lar_TestClassUtility.createCustomerPromptInstance(prompt, client, 'Interim', 'Prompt');
        customerPrompt.Last_Action_Owner_User__c=u2.id;
        customerPrompt.Interim_Action_Date__c = Date.Today() + 31;
        
        insert customerPrompt;
        
        Opportunity opportunity = lar_TestClassUtility.createOpportunityInstance(client, 'Test Opp', 'In progress', system.today()+1, 'Current Account', 'Blue Rewards', 'Product');   
        opportunity.Type='New Business';
        opportunity.Retention_or_new_business__c='New';
        insert opportunity;
        
        Test.startTest();
        //Database.executeBatch(new lar_BatchConvertInterimPromptsToOpp());
        lar_BatchConvertInterimPromptsToOpp batchCIP = new lar_BatchConvertInterimPromptsToOpp(); 
        batchCIP.execute(null);
        Test.stopTest();
        
        
    }
}