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
Robert Davis 1Robert Davis 1 

Test Class for Batchable Apex Class - Execute Method

I am new to the Apex and am see if someone can help me understand how I go about testing a method that gets its data from a List that is an sObject when the parameter that I pass in is the String of the query. I am having trouble figuring out how to get the execute method to test successfully.

The following is my Apex Batchable Class:
 
global class MyBatchJob implements Database.Batchable<sObject>{

    global string query;

       
    global MyBatchJob(){
        String query = 'SELECT      account.id, ' +
                                   'account.name, ' +
                                   'account.industry, ' +
                                   'account.ownerId, ' +
                                   'account.owner.firstname,' +
                                   'account.owner.lastname,'+
                                   'account.recordtypeid, '+
                                   'account.recordtype.name,' +
                                   'account.type, ' +
                                   'Level_of_Effort__c,' +
                                   'Name, ' +
                                   'Ownerid, ' +
                                   'Owner.firstname, ' + 
                                   'Owner.lastname, ' +
                                   'Solution_Complexity__c, ' +
                                   'StageName, '+
                                   'Annualized_Revenue__c,' +
                                   'Amount, ' +
                                   'FTEs__c, ' +
                                   'TotalNumberofSeats__c ' +                              
                                   'FROM Opportunity';     
    } 

    global Database.QueryLocator start(Database.BatchableContext BC){
        System.debug('Started the Batch job to copy key Opportunity Record fields.');
        System.debug('The current Batch unique identifier for this job is : '+ BC.getJobId());
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC,List<Opportunity> scope) {
        System.debug('Executed the Batch job to copy Opportunity Records.');
        System.debug('The current Batch unique identifier for this job is : '+ BC.getJobId());
        List<Opportunity_Snapshot__c> snapList = new List<Opportunity_Snapshot__c>();

                 //Assuming the snapshots you want are of Contact data
		        for(Opportunity opp: scope) {
                 //create a sObject NOT an sObject List to hold the data until I add to the List with snapList.add(snap)
                 //This is a lot like creating a JSON framework in Javascript
                    Opportunity_Snapshot__c snap = new Opportunity_Snapshot__c();
            
                    //start adding to the snap variable from the query results
                    snap.Ss_Account_Id__c                       = opp.AccountId;
                    snap.Ss_Account_Industry__c                 = opp.Account.Industry;
                    snap.Ss_Account_Name__c                     = opp.Account.Name;
                    snap.Ss_Account_Owner_Id__c                 = opp.Account.OwnerId;
                    snap.Ss_Account_Owner_Name__c               = opp.Account.Owner.Firstname + ' ' + opp.Owner.Lastname;
                    snap.Ss_Account_Recordtype_Id__c            = opp.account.recordtypeid;
                    snap.Ss_Account_Recordtype_Name__c          = opp.account.recordtype.name;
                    snap.Ss_Account_Type__c                     = opp.Account.Type;
                    snap.Ss_Opportunity_Amount__c               = opp.Amount;
                    snap.Ss_Opportunity_Annualized_Revenue__c   = opp.Annualized_Revenue__c;
                    snap.Ss_Opportunity_Level_of_Effort__c      = opp.Level_of_Effort__c;
                    snap.Ss_Opportunity_Name__c                 = opp.Name;
                    snap.Ss_Opportunity_Owner_Id__c             = opp.Ownerid;
                    snap.Ss_Opportunity_Owner_Name__c           = opp.Owner.firstname + ' ' + opp.Owner.lastname;
                    snap.Ss_Opportunity_Solution_Complexity__c  = opp.Solution_Complexity__c;
                    snap.Ss_Opportunity_Stage_Name__c           = opp.StageName;
                    snap.Ss_Opportunity_Total_FTE__c            = opp.FTEs__c;
                    snap.Ss_Opportunity_Total_Seats__c          = opp.TotalNumberofSeats__c;

                    //Let's now add these variables to the list to be inserted at the end of the loop.
                    snapList.add(snap); 
  
          
        } 
        insert snapList; 
   }

   global void finish(Database.BatchableContext BC) {
        System.debug(LoggingLevel.WARN,'Batch Job is Complete!!!!!');
        
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[]{'any@gmail.com', 'any@outlook.com'};
        mail.setToAddresses(toAddresses);
        mail.setSubject('Email Batch Worked');
        mail.setPlainTextBody ('Batch Job worked');
    }
}
So far I have 29% successfully tested.
 
@isTest
public class TestMyBatchJob {
    public static testmethod void TestBatchJob(){
        Test.startTest();
        MyBatchJob bj = new MyBatchJob();
        bj.query=      'SELECT      account.id, ' +
                                   'account.name, ' +
                                   'account.industry, ' +
                                   'account.ownerId, ' +
                                   'account.owner.firstname,' +
                                   'account.owner.lastname,'+
                                   'account.recordtypeid, '+
                                   'account.recordtype.name,' +
                                   'account.type, ' +
                                   'Level_of_Effort__c,' +
                                   'Name, ' +
                                   'Ownerid, ' +
                                   'Owner.firstname, ' + 
                                   'Owner.lastname, ' +
                                   'Solution_Complexity__c, ' +
                                   'StageName, '+
                                   'Annualized_Revenue__c,' +
                                   'Amount, ' +
                                   'FTEs__c, ' +
                                   'TotalNumberofSeats__c ' +                                
                                   'FROM Opportunity';        
        ID batchprocessid = Database.executeBatch(bj);

        Test.stopTest();
   
       }


	public static void testBatch() 
	     {
	        List<Opportunity_Snapshot__c> testSnaplist = new List<Opportunity_Snapshot__c>();
        
            Opportunity_Snapshot__c testSnap = new Opportunity_Snapshot__c();
		    for(Integer i = 0 ; i < 200; i++){
		        testSnap.Ss_Account_Id__c                       = 'ID123425'+i;
                testSnap.Ss_Account_Industry__c                 = 'Offshoring and Nearshoring Test';
                testSnap.Ss_Account_Name__c                     = 'Test Account Name'+i;
                testSnap.Ss_Account_Owner_Id__c                 = 'Account Owner Test '+i;
                testSnap.Ss_Account_Owner_Name__c               = 'Test J Tester '+i*157469;
                testSnap.Ss_Account_Recordtype_Id__c            = 'Record Type Id123456789012345678901234567890123456789' +i;
                testSnap.Ss_Account_Recordtype_Name__c          = 'Record Type Name ' +i;
                testSnap.Ss_Account_Type__c                     = 'Account Prospect '+i;
                testSnap.Ss_Opportunity_Amount__c               =  451+i;
                testSnap.Ss_Opportunity_Annualized_Revenue__c   = 12+i;
                testSnap.Ss_Opportunity_Level_of_Effort__c      = 26+i;
                testSnap.Ss_Opportunity_Name__c                 = 'Test Opportunity Name ' +i;
                testSnap.Ss_Opportunity_Owner_Id__c             = 'Opportunity Owner Test ID'+i;
                testSnap.Ss_Opportunity_Owner_Name__c           = 'Sammy the Tester';
                testSnap.Ss_Opportunity_Solution_Complexity__c  = 'High';
                testSnap.Ss_Opportunity_Stage_Name__c           = 'Test Opportunity Stage ' +i;
                testSnap.Ss_Opportunity_Total_FTE__c            = 12;
                testSnap.Ss_Opportunity_Total_Seats__c          = 37;    
            
                testSnaplist.add(testSnap);

		}

		insert testSnaplist;
	   
		Test.StartTest();
               MyBatchJob bj2 = new MyBatchJob();
        
		ID batchprocessid = Database.executeBatch(bj2);
		   
		Test.StopTest();
		
		
	}
}
Your help is greatly appreciated.

Robert

 
Best Answer chosen by Robert Davis 1
SotosSotos
Hi Robert,

In your test you are inserting Opportunity_Snapshot__c objects whilst the batch is querying Oppotrunity objects in the start method,
so Opportunity sObjects are in the scope as well. Thus, I believe that the for loop in the execute method is not executed and the lines are not covered. 

Also your tests do not verify that the batch did its job sucessfully. The just call it. I woulld suggest to have a read on the documentation on how to unit test the batch class https://developer.salesforce.com/docs/atlas.en-us.apex_workbook.meta/apex_workbook/apex_batch_2.htm (https://developer.salesforce.com/docs/atlas.en-us.apex_workbook.meta/apex_workbook/apex_batch_2.htm" target="_blank) to help you get going :)

Hope this helps.

All Answers

SotosSotos
Hi Robert,

In your test you are inserting Opportunity_Snapshot__c objects whilst the batch is querying Oppotrunity objects in the start method,
so Opportunity sObjects are in the scope as well. Thus, I believe that the for loop in the execute method is not executed and the lines are not covered. 

Also your tests do not verify that the batch did its job sucessfully. The just call it. I woulld suggest to have a read on the documentation on how to unit test the batch class https://developer.salesforce.com/docs/atlas.en-us.apex_workbook.meta/apex_workbook/apex_batch_2.htm (https://developer.salesforce.com/docs/atlas.en-us.apex_workbook.meta/apex_workbook/apex_batch_2.htm" target="_blank) to help you get going :)

Hope this helps.
This was selected as the best answer
Robert Davis 1Robert Davis 1
Sotos,

Thank you for the insights. I will continue working and thank you for the links.

Robert
Robert Davis 1Robert Davis 1
This is the test class that ended up working:
 
@isTest
public class TestMyBatchJob {
    public static testmethod void TestBatchJob(){
        Schema.DescribeSObjectResult cfrSchema = Schema.SObjectType.Account; 
        Map<String,Schema.RecordTypeInfo> AccountRecordTypeInfo = cfrSchema.getRecordTypeInfosByName();

             Profile prof = [select id from profile where name='system Administrator'];
             User usr = new User(alias = 'usr', email='us.name@vmail.com',
                emailencodingkey='UTF-8', lastname='lstname',
                timezonesidkey='America/Los_Angeles',
                languagelocalekey='en_US',
                localesidkey='en_US', profileid = prof.Id,
                username='testuser128@testorg.com',MobilePhone='87564231',Phone='451234789');
                insert usr;
             Account accRec = new Account(name='testName', Ownerid = usr.id,recordtypeid=AccountRecordTypeInfo.get('Prospect').getRecordTypeId());
             insert accRec;
              Schema.DescribeSObjectResult cfrSchema1 = Schema.SObjectType.Opportunity; 
            Map<String,Schema.RecordTypeInfo> opportunityRecordTypeInfo = cfrSchema1.getRecordTypeInfosByName();
            list<opportunity> oppList = new list<opportunity>();
             for(Integer i = 0 ; i < 200; i++){
                 Opportunity oppObj = new Opportunity();
                oppObj.recordtypeid=opportunityRecordTypeInfo.get('Core Products').getRecordTypeId();
                oppObj.AccountId=accRec.id;
                oppObj.Name ='Jacob's Lettering - Customer Care'+i;
                oppObj.Type ='New';
                oppObj.CloseDate =system.today()+5;
                oppObj.StageName ='1 - Prospect'ing;
                oppObj.CurrencyIsoCode='USD';
                oppObj.LeadSource='Marketing - Logisitcsl';
                oppList.add(oppObj);
                
             }
             if(!oppList.isEmpty()){
                 insert oppList;
             }
             System.assertEquals(200,oppList.size());
     
    Test.StartTest();
           MyBatchJob bj2 = new MyBatchJob();
           bj2.query='SELECT      account.id, ' +
                                   'account.name, ' +
                                   'account.industry, ' +
                                   'account.ownerId, ' +
                                   'account.owner.firstname,' +
                                   'account.owner.lastname,'+
                                   'account.recordtypeid, '+
                                   'account.recordtype.name,' +
                                   'account.type, ' +
                                   'Level_of_Effort__c,' +
                                   'Name, ' +
                                   'Ownerid, ' +
                                   'Owner.firstname, ' + 
                                   'Owner.lastname, ' +
                                   'Solution_Complexity__c, ' +
                                   'StageName, '+
                                   'Annualized_Revenue__c,' +
                                   'Amount, ' +
                                   'FTEs__c, ' +
                                   'TotalNumberofSeats__c ' +                              
                                   'FROM Opportunity';   
           ID batchprocessid = Database.executeBatch(bj2);
        Test.StopTest();

  }
}