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
tonantetonante 

ExecuteBatch() method is not invoked when testing Batch Test Class

HI , when testing batch class , may test doesn;t seem to be invoking the executeBatch() method even though it does have a valid list of opportunities for the scope. I traced the code flow in debug log to where it finished the start method in creating the QueryLocator and saw that it did contain a list of opportunities but it did not reach the executeBatch method but skipped ahead to the finish method. So now I am  only able to cover 53%.  I wonder why the Query Locator skipped to Finish upon return? Doesn;t it flow into executeBatch if the object for scope is not empty?  Here is my class code for batch: 
global class BatchGeneratePickTicketsByQuery implements Database.Batchable<sObject>
{
    global String Query;

    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        String DefaultQuery = 
            ' Select Id, AccountId, Account.Name, RecordTypeId, RecordType.Name, Name, ' + 
            ' StageName, Amount, CreatedDate, CreatedById, CreatedBy.Name, HasOpportunityLineItem, LastModifiedDate, ' +
            ' LastModifiedById, LastModifiedBy.Name, TotalOpportunityQuantity, Total_Pick_Quantity__c, ' +
            ' Total_Pick_Tickets__c, Inventory_Items__c, Non_inventory_Items__c, Error_Log__c, ' +
            ' (Select Id, Name From Pick_Tickets__r) ' + 
            ' FROM Opportunity Where CreatedDate > 2012-07-01T00:00:00.000Z ' +
            ' And RecordType.Name = \'Orders\' ' + 
            ' And Amount > 0 ' + 
            ' And (StageName = \'Order Confirmed\' OR StageName like \'%Partially%\') ' + 
            ' And (NOT StageName like \'%Cancelled%\') ' + 
            ' And Id Not In (Select Opportunity__c From Sales_Order__c) ';
    
        if(Query == null) {
           Query = DefaultQuery; 
        }
        else {
            system.debug('<<QUERY>> '+Query);
            if(!Query.toLowerCase().contains('from opportunity')) { Query = null; } 
        }
        
        system.debug('QUERY >> '+Query);
        
        return Database.getQueryLocator(Query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
        for(sObject s : scope)
        {
            Opportunity o = (Opportunity)s;
            OrderEntryStatus.QueueGeneratePickTicket(o.Id);
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        system.debug(BC);
    }
}
 2) Here is the Test Class for the batch class:
 
@isTest
public class BatchGeneratePickTicketsByQuery_Test {
	static testmethod void test() {
String Query =
      ' Select Id, AccountId, Account.Name, RecordTypeId, RecordType.Name, Name, ' + 
          ' StageName, Amount, CreatedDate, CreatedById, CreatedBy.Name, HasOpportunityLineItem, LastModifiedDate, ' +
          ' LastModifiedById, LastModifiedBy.Name, TotalOpportunityQuantity, Total_Pick_Quantity__c, Company__c,Shipping_Weight__c, ' +
          ' Total_Pick_Tickets__c, Inventory_Items__c, Non_inventory_Items__c, Error_Log__c ' + 
          ' FROM Opportunity Where CreatedDate > 2012-07-01T00:00:00.000Z ' +
          ' And RecordType.Name = \'Orders\' ' + 
      ' And Amount >= 0 ' + 
      ' And (Total_Pick_Tickets__c > 0 OR Pick_Ticket_Not_Fulfillable__c = true) ' + 
      ' And StageName != \'Order Cancelled\' ' + 
      ' And StageName != \'Order Invoiced\' ' + 
      ' And (Not StageName like \'%Fulfilled%\') ' + 
      ' And (StageName like \'%Partially%\' OR StageName = \'Order Confirmed\' OR Pick_Ticket_Not_Fulfillable__c = true) ' + 
      ' And Id Not In (Select Opportunity__c From Sales_Order__c)';
		
		Test.startTest();	
        BatchGeneratePickTicketsByQuery bgptbq = new BatchGeneratePickTicketsByQuery();
        bgptbq.Query= null;
        ID batchprocessid = Database.executeBatch(bgptbq);
		Test.stopTest();
    }
}

Thanks  for your help.

 
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class. I hope that will help u
@isTest()
public class BatchGeneratePickTicketsByQuery_Test {
	static testmethod void test() {
	
	
		Account acc= new Account(Name = 'testAcc',BillingStreet='testStreet',BillingCity ='tectcity',BillingState='testState',BillingPostalCode='123',
                                   BillingCountry='testcountry',Description='testdesc');
       insert acc;

        //Case record in Test method. 
        Contact conObj = new Contact();
        conObj.lastname = 'testcon';
        conObj.AccountId = acc.id;
        insert conObj;
    
        Opportunity opp= new Opportunity(AccountId=acc.id,Amount=1234.00,Description='testdesc',Name='testOpp',
                                         StageName='Prospecting',CloseDate = System.Today());
        insert opp;
	   
	
		String Query =
		' Select Id, AccountId, Account.Name, RecordTypeId, RecordType.Name, Name, ' + 
          ' StageName, Amount, CreatedDate, CreatedById, CreatedBy.Name, HasOpportunityLineItem, LastModifiedDate, ' +
          ' LastModifiedById, LastModifiedBy.Name, TotalOpportunityQuantity, Total_Pick_Quantity__c, Company__c,Shipping_Weight__c, ' +
          ' Total_Pick_Tickets__c, Inventory_Items__c, Non_inventory_Items__c, Error_Log__c ' + 
          ' FROM Opportunity ' ;
		
		Test.startTest();	
        BatchGeneratePickTicketsByQuery bgptbq = new BatchGeneratePickTicketsByQuery();
        bgptbq.Query= Query;
        ID batchprocessid = Database.executeBatch(bgptbq);
		Test.stopTest();
    }
}
Please let us know if this will help u
 
tonantetonante
Thanks Amit that really did it. Now my coverage is up to 92%. I completely forgot to fill out the parent objects for the opportuhnity by creating the account and fake contact first.  However that is inetersting that this didn;t work because I have another class which is similar to it that only needed the crreation of the opportunity in the start method however it did use an iterator. I am wondering if that made the difference and if so... why? Here is the code for that one
global class BatchGeneratePickTickets implements Database.Batchable<sObject>
{
    global String Query;
	global List<Opportunity> OrdersToPick;
	
    global Iterable<sObject> start(Database.BatchableContext BC)
    {
    	// if the list provided is null, it must be generated
    	if(OrdersToPick == null)
    	{
	        String DefaultQuery = 
	            ' Select Id, AccountId, Account.Name, RecordTypeId, RecordType.Name, Name, ' + 
	            ' StageName, Amount, CreatedDate, CreatedById, CreatedBy.Name, HasOpportunityLineItem, LastModifiedDate, ' +
	            ' LastModifiedById, LastModifiedBy.Name, TotalOpportunityQuantity, Total_Pick_Quantity__c, ' +
	            ' Total_Pick_Tickets__c, Inventory_Items__c, Non_inventory_Items__c, Error_Log__c, ' +
	            ' (Select Id, Name From Pick_Tickets__r) ' + 
	            ' FROM Opportunity Where CreatedDate > 2010-07-01T00:00:00.000Z ' +
	            ' And RecordType.Name = \'Orders\' ' + 
	            ' And Amount > 0 ' + 
	            ' And (StageName = \'Order Confirmed\' OR StageName like \'%Partially%\') ' + 
	            ' And (NOT StageName like \'%Cancelled%\') ' + 
	            ' And Id Not In (Select Opportunity__c From Sales_Order__c) ';
	    
	        if(Query == null) {
	            Query = DefaultQuery; }
	        else {
	            if(!Query.toLowerCase().contains('from opportunity')) { Query = null; } }
	        
	        system.debug(Query);
	        
	        OrdersToPick = Database.query(Query);
    	}
        
        CustomIterable OrdersToPickIterable = new CustomIterable(OrdersToPick);
        
        system.debug('Custom Iterable: '+OrdersToPickIterable);
        
		return OrdersToPickIterable;
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope)
    {
        for(sObject s : scope)
        {
        	Opportunity o = (Opportunity)s;
        	OrderEntryStatus.QueueGeneratePickTicket(o.Id);
        }
    }
    
    global void finish(Database.BatchableContext BC)
    {
        system.debug(BC);
    }

Just curious about the difference because to test this one successfully at 93% I just ran this:
@isTest
public class BatchGeneratePickTicket_Test {
    static testMethod void testTickets() {
	String query =    ' Select Id, AccountId, Account.Name, RecordTypeId, RecordType.Name, Name, ' + 
	            ' StageName, Amount, CreatedDate, CreatedById, CreatedBy.Name, HasOpportunityLineItem, LastModifiedDate, ' +
	            ' LastModifiedById, LastModifiedBy.Name, TotalOpportunityQuantity, Total_Pick_Quantity__c, ' +
	            ' Total_Pick_Tickets__c, Inventory_Items__c, Non_inventory_Items__c, Error_Log__c, ' +
	            ' (Select Id, Name From Pick_Tickets__r) ' + 
	            ' FROM Opportunity Where CreatedDate > 2010-07-01T00:00:00.000Z ' +
	            ' And RecordType.Name = \'Orders\' ' + 
	            ' And Amount > 0 ' + 
	            ' And (StageName = \'Order Confirmed\' OR StageName like \'%Partially%\') ' + 
	            ' And (NOT StageName like \'%Cancelled%\') ' + 
	            ' And Id Not In (Select Opportunity__c From Sales_Order__c) ';


		Test.startTest();
		Database.executeBatch(new BatchGeneratePickTickets());
		Test.stopTest();
    }
}


 
Amit Chaudhary 8Amit Chaudhary 8
Please try below test class
@isTest()
public class BatchGeneratePickTicketsTest 
{
	static testmethod void test() 
	{
	
	
		Account acc= new Account(Name = 'testAcc',BillingStreet='testStreet',BillingCity ='tectcity',BillingState='testState',BillingPostalCode='123',
                                   BillingCountry='testcountry',Description='testdesc');
       insert acc;

        //Case record in Test method. 
        Contact conObj = new Contact();
        conObj.lastname = 'testcon';
        conObj.AccountId = acc.id;
        insert conObj;
    
		List<Opportunity> lstOpp = new List<Opportunity>();
		
        Opportunity opp= new Opportunity(AccountId=acc.id,Amount=1234.00,Description='testdesc',Name='testOpp',
                                         StageName='Prospecting',CloseDate = System.Today());
        insert opp;
	    lstOpp.add(opp);
	
		String Query =
		' Select Id, AccountId, Account.Name, RecordTypeId, RecordType.Name, Name, ' + 
          ' StageName, Amount, CreatedDate, CreatedById, CreatedBy.Name, HasOpportunityLineItem, LastModifiedDate, ' +
          ' LastModifiedById, LastModifiedBy.Name, TotalOpportunityQuantity, Total_Pick_Quantity__c, Company__c,Shipping_Weight__c, ' +
          ' Total_Pick_Tickets__c, Inventory_Items__c, Non_inventory_Items__c, Error_Log__c ' + 
          ' FROM Opportunity ' ;

		  
		Test.startTest();	
        BatchGeneratePickTickets bgptbq = new BatchGeneratePickTickets();
        bgptbq.Query= Query;
		bgptbq.OrdersToPick = lstOpp;
		
        ID batchprocessid = Database.executeBatch(bgptbq);
		Test.stopTest();
    }
}
Please let us know if this will hep u