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
Luke Higgins 22Luke Higgins 22 

Help with a Test Class for Batch

What I have so far covers 26% of the batch class. I'm not able to cover the execute portion of the batch class.

batch.cls
public class Batch implements Database.Batchable<sObject> {

	public Database.QueryLocator start(Database.BatchableContext bc) {
        String query = 'SELECT Id, jstcl__Consultant__r.Previous_Timesheet_Status__c FROM jstcl__TG_Timesheet__c WHERE jstcl__Placement__r.ts2__Status__c =\'Active\' AND jstcl__Placement__r.VMS__c = \'\' AND jstcl__Week_Ending__c = LAST_N_DAYS:4 AND jstcl__Status__c = \'Pending\'';
          return Database.getQueryLocator(query);
    }
   public void execute(Database.BatchableContext BC, List<jstcl__TG_Timesheet__c> timesheets){
       List<Contact> consultants = new List<Contact>();
       List<Contact> consultants2 = new List<Contact>();

       for(jstcl__TG_Timesheet__c timesheet : timesheets){
           Contact consultant = timesheet.jstcl__Consultant__r; 
           if (consultant == null) continue;
           consultant.Previous_Timesheet_Status__c = 'Pending';
           if(consultants.contains(consultant)){
               consultants2.add(consultant);
           }else{consultants.add(consultant);}
           }
           update consultants;
        }
   public void finish(Database.BatchableContext BC){}
}
test.cls
@istest 
private class Test {

static TestMethod void hfTest() {
     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');
                insert usr;
    Id idRecordId = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Candidate').getRecordTypeId();

    	ts2__Source__c source = new ts2__Source__c(Name = 'LinkedIn.com - Resume Search');
    	Account acc = new Account(Name = 'Express Scripts Holding Company');
        insert acc;
  		Account acc2 = new Account(Name = 'Candidates- 10-2018');
        insert acc2;
    	Contact con = new Contact(FirstName='fnadmes', LastName = 'lnamdes', Email = 'emadils@gmail.com', Phone = '9744800300', AccountId = acc2.Id, ts2__Source__c = source.Id, ts2__People_Status__c = 'Placed');
        Contact con2=new Contact(FirstName='fnames', LastName = 'lnames', Email = 'emails@gmail.com', Phone = '9743800300', AccountId=acc.Id, Relationship_Status__c = 'Lunch'); 
    	insert con; insert con2;
        ADP_Department__c adp = new ADP_Department__c(Name = 'Georgia');
        insert adp;
        ts2__Job__c job = new ts2__Job__c(Name = 'Software Engineer',Hiring_Manager_Contact__c = con2.Id);
        insert job;
        ts2__HolidayCalendar__c hcal = new ts2__HolidayCalendar__c(Name= 'Holiday Calendar');
        insert hcal;
        Labor_Category__c lcat = new Labor_Category__c(Name='Software Engineer 1');  
        insert lcat;
        ts2__Placement__c plc = new ts2__Placement__c(ts2__Job__c = job.Id, Contractor_Type__c = 'Technical Youth', Onboarding_Method__c= 'Staff Augmentation', ts2__Start_Date__c= Date.newInstance(2019, 1, 7), ts2__End_Date__c= Date.newInstance(2019, 2, 15),
        jstcl__HireType__c= 'W2', ADP_Department__c= adp.Id, ts2__Bill_Rate__c= 60.00, ts2__Pay_Rate__c= 30.00, jstcl__Invoice_Batch__c= 'Placement', ts2__Client__c= acc.Id, ts2__Hiring_Manager__c= con2.Id, jstcl__TimecardApprover__c= con2.Id, jstcl__HolidayCalendar__c= hcal.Id,
		State_Worked_In_Non_TFI_Placements__c= 'GA - Georgia', jstcl__Overtime_Bill_Rate__c= 60, jstcl__Burden__c= 0.20, jstcl__Accounts_Receivable_U__c= '00537000005d7F2AAI', jstcl__Terms__c= 'Net 60', ts2__Employee__c= con.Id, Labor_Category__c= lcat.Id);
		insert plc;
     	List<jstcl__TG_Timesheet__c> tsList = new List<jstcl__TG_Timesheet__c>();
    	 jstcl__TG_Timesheet__c ts = new jstcl__TG_Timesheet__c(jstcl__Consultant__c = con2.Id, jstcl__Placement__c = plc.Id, jstcl__Week_Ending__c = Date.newInstance(2019, 2, 15));
    tsList.add(ts);

	Test.startTest(); 
     Batch abcd = new Batch();
     ID batchprocessid = Database.executeBatch(abcd);
	Test.stopTest();
 }    
}

 
SRKSRK

i see you created a list of jstcl__TG_Timesheet__c but you never inserted that list 
insert that list and that might solve your problem

List<jstcl__TG_Timesheet__c> tsList = new List<jstcl__TG_Timesheet__c>();
     jstcl__TG_Timesheet__c ts = new jstcl__TG_Timesheet__c(jstcl__Consultant__c = con2.Id, jstcl__Placement__c = plc.Id, jstcl__Week_Ending__c = Date.newInstance(2019, 2, 15));
    tsList.add(ts);

 

insert tsList

PRAKASH JADA 13PRAKASH JADA 13
Hi,

you can create your test class like this to improve your code coverage
@isTest(seeAllData = false)
public with sharing class Test {

    // Preparing the mock test data
    @isTest static void hfTest() {
        // Insert user
        Profile p = [SELECT Id FROM Profile WHERE Name = 'system Administrator'];

        User user           = 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');
        
        // Insert dependency Objects
        // Insert jstcl__Placement__c with the test data that matching the batch class 
        
        // Insert the test data for jstcl__TG_Timesheet__c that matching the batch class conditions
        
        // Add some system.assert's so that you that the test data is created appropriately.
        
        Test.startTest();
        Database.execute(new Batch(), 200);
        Test.stopTest();        
    }

}

// it will give you more 90% of your test coverage

I hope this helps you to improve your test coverage.
 
Niraj Kr SinghNiraj Kr Singh
Hi Luke,
Hope you are doing well !!
You have missed only small things in you code. I have corrected and added the relavent comments as well to understand well ( you will find in BOLD letter inside code).
@istest (seeAllData=false)
private class Test {

static TestMethod void hfTest() {
    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');
    insert usr;
    Id idRecordId = Schema.SObjectType.Contact.getRecordTypeInfosByDeveloperName().get('Candidate').getRecordTypeId();

    	ts2__Source__c source = new ts2__Source__c(Name = 'LinkedIn.com - Resume Search');
    	Account acc = new Account(Name = 'Express Scripts Holding Company');
        insert acc;
  		Account acc2 = new Account(Name = 'Candidates- 10-2018');
        insert acc2;
    	Contact con = new Contact(FirstName='fnadmes', LastName = 'lnamdes', Email = 'emadils@gmail.com', Phone = '9744800300', AccountId = acc2.Id, ts2__Source__c = source.Id, ts2__People_Status__c = 'Placed');
        Contact con2=new Contact(FirstName='fnames', LastName = 'lnames', Email = 'emails@gmail.com', Phone = '9743800300', AccountId=acc.Id, Relationship_Status__c = 'Lunch'); 
    	insert con; insert con2;
        ADP_Department__c adp = new ADP_Department__c(Name = 'Georgia');
        insert adp;
        ts2__Job__c job = new ts2__Job__c(Name = 'Software Engineer',Hiring_Manager_Contact__c = con2.Id);
        insert job;
        ts2__HolidayCalendar__c hcal = new ts2__HolidayCalendar__c(Name= 'Holiday Calendar');
        insert hcal;
        Labor_Category__c lcat = new Labor_Category__c(Name='Software Engineer 1');  
        insert lcat;
        ts2__Placement__c plc = new ts2__Placement__c(ts2__Job__c = job.Id, Contractor_Type__c = 'Technical Youth', Onboarding_Method__c= 'Staff Augmentation', ts2__Start_Date__c= Date.newInstance(2019, 1, 7), ts2__End_Date__c= Date.newInstance(2019, 2, 15),
        jstcl__HireType__c= 'W2', ADP_Department__c= adp.Id, ts2__Bill_Rate__c= 60.00, ts2__Pay_Rate__c= 30.00, jstcl__Invoice_Batch__c= 'Placement', ts2__Client__c= acc.Id, ts2__Hiring_Manager__c= con2.Id, jstcl__TimecardApprover__c= con2.Id, jstcl__HolidayCalendar__c= hcal.Id,
		State_Worked_In_Non_TFI_Placements__c= 'GA - Georgia', jstcl__Overtime_Bill_Rate__c= 60, jstcl__Burden__c= 0.20, jstcl__Accounts_Receivable_U__c= '00537000005d7F2AAI', jstcl__Terms__c= 'Net 60', ts2__Employee__c= con.Id, Labor_Category__c= lcat.Id);
		insert plc;
     	List<jstcl__TG_Timesheet__c> tsList = new List<jstcl__TG_Timesheet__c>();
    	 jstcl__TG_Timesheet__c ts = new jstcl__TG_Timesheet__c(jstcl__Consultant__c = con2.Id, jstcl__Placement__c = plc.Id, jstcl__Week_Ending__c = Date.newInstance(2019, 2, 15));
    tsList.add(ts);
	
        //Another record added.
	tsList.add(new jstcl__TG_Timesheet__c(jstcl__Consultant__c = con2.Id, jstcl__Placement__c = plc.Id, jstcl__Week_Ending__c = Date.newInstance(2019, 2, 16)));
	
	//You have not inserted the the list 'tsList' for which you are runing the batch.
	//Hints: Add 1 or 2 more records in the list 'tsList' to cover else part part as well. Like added above here.
	insert tsList;
	
	Test.startTest(); 
		Batch abcd = new Batch();
		ID batchprocessid = Database.executeBatch(abcd);
	Test.stopTest();
 }    
}



Hope it will help you out.
Thanks,
Niraj
Luke Higgins 22Luke Higgins 22
None of these suggestions have solved the issue. I am still stuck at 26% with the following part not being covered - 
global void execute(Database.BatchableContext BC, List<jstcl__TG_Timesheet__c> timesheets){
       List<Contact> consultants = new List<Contact>();
       List<Contact> consultants2 = new List<Contact>();

       for(jstcl__TG_Timesheet__c timesheet : timesheets){
           Contact consultant = timesheet.jstcl__Consultant__r; 
           if (consultant == null) continue;
           consultant.Previous_Timesheet_Status__c = 'Pending';
           if(consultants.contains(consultant)){
               consultants2.add(consultant);
           }else{consultants.add(consultant);}
           }
           update consultants;
        }
SRKSRK

you have following four fields in you ware clause

jstcl__Placement__r.ts2__Status__c =\'Active\' AND jstcl__Placement__r.VMS__c = \'\' AND jstcl__Week_Ending__c = LAST_N_DAYS:4 AND jstcl__Status__c = \'Pending\'';

and you are missing these 4 field when you are inserting ts2__Placement__c datain test calss i trying add it below so try updating in your test class and see if that work

you need to insert "ts2__Placement__c" data in you test class such that it will full fill below mentioen condtion
jstcl__Placement__r.ts2__Status__c =\'Active\' AND jstcl__Placement__r.VMS__c = \'\' AND jstcl__Week_Ending__c = LAST_N_DAYS:4 AND jstcl__Status__c = \'Pending\'';

ts2__Placement__c plc = new ts2__Placement__c(ts2__Status__c = 'Active',VMS__c ='',jstcl__Week_Ending__c =system.today.adddays(-3), jstcl__Status__c ='Pending',ts2__Job__c = job.Id, Contractor_Type__c = 'Technical Youth', Onboarding_Method__c= 'Staff Augmentation', ts2__Start_Date__c= Date.newInstance(2019, 1, 7), ts2__End_Date__c= Date.newInstance(2019, 2, 15),
        jstcl__HireType__c= 'W2', ADP_Department__c= adp.Id, ts2__Bill_Rate__c= 60.00, ts2__Pay_Rate__c= 30.00, jstcl__Invoice_Batch__c= 'Placement', ts2__Client__c= acc.Id, ts2__Hiring_Manager__c= con2.Id, jstcl__TimecardApprover__c= con2.Id, jstcl__HolidayCalendar__c= hcal.Id,
       State_Worked_In_Non_TFI_Placements__c= 'GA - Georgia', jstcl__Overtime_Bill_Rate__c= 60, jstcl__Burden__c= 0.20, jstcl__Accounts_Receivable_U__c= '00537000005d7F2AAI', jstcl__Terms__c= 'Net 60', ts2__Employee__c= con.Id, Labor_Category__c= lcat.Id);

     insert plc;

 

 


   tsList.add(new jstcl__TG_Timesheet__c(jstcl__Consultant__c = con2.Id, jstcl__Placement__c = plc.Id, jstcl__Week_Ending__c = Date.newInstance(2019, 2, 16)));
   
 insert tsList;</b>

Andrew GAndrew G
Try tweaking the code sample by Nirag
 
    insert tsList;

    Test.startTest();
       Batch abcd = new Batch();
       ID batchprocessid = Database.executeBatch(abcd, tsList);
    Test.stopTest();
If i understand batching correctly, your execute code is expecting context and list of objects.
execute(Database.BatchableContext BC, List<jstcl__TG_Timesheet__c> timesheets)
So your test execute call needs to be in the same format.

Happy to be corrected.

Regards
Andrew
 
SRKSRK

in start he is running a query on "jstcl__TG_Timesheet__c " where he have a condtion saying that related record of "jstcl__Placement__r" 
with timesheet should have ts2__Status__c = 'Active' and VMS__c = '' and there is afield on time record it self "jstcl__Week_Ending__c " that should be 4 day from today and another field on time record jstcl__Status__c = "pending'

but the test data he created  for jstcl__Placement__r in test class do not full fill this condtion (i.e.  ts2__Status__c = 'Active' and VMS__c = '')