2

I have a batch class that needs a test class. In creating the test records, the insertion of a necessary object record triggers a Chatter Post via another trigger. That chatter post references a CollaborationGroup and uses the ConnectApi feature so I have to use (SeeAllData=True).

The problem is that by using the (SeeAllData=True) declaration, I get the error message

No more than one executeBatch can be called from within a testmethod

If I use the (SeeAllData=True) declaration, my test fails. If I don't use the (SeeAllData)=True declaration, my test fails. If I use the (!test.isRunningTest) method to skip this, my code coverage falls below 75%.

I'm in a predicament and need to figure out a way to test my batch class that also triggers a series of Chatter Posts at the same time.

Any suggestions would be greatly appreciated!

1 Answer 1

0

Alright, so I figured out a workaround, I used the test.isRunningTest to help build/limit my query.

global Database.QueryLocator start(Database.BatchableContext BC){
        string query;
        if(!test.isRunningTest()){
            query =  'SELECT Id, Name, Flight_Start_Date__c, Flight_End_Date__c, Budget__c, vCPM__c, Campaign_Execution_Type__c,(SELECT ID, Budget__c, Flight_Start_Date__c, Flight_End_Date__c, vCPM__c, Campaign_Execution_Type__c, LastModifiedDate FROM Campaign_Flights__r) FROM Campaign_Line_Item__c';
        }
        else{
            query =  'SELECT Id, Name, Flight_Start_Date__c, Flight_End_Date__c, Budget__c, vCPM__c, Campaign_Execution_Type__c,(SELECT ID, Budget__c, Flight_Start_Date__c, Flight_End_Date__c, vCPM__c, Campaign_Execution_Type__c, LastModifiedDate FROM Campaign_Flights__r) FROM Campaign_Line_Item__c Limit 10';
        }
        return Database.getQueryLocator(query);
    } 
4
  • That's still going to mess up your coverage... have you tried simply inserting a new CollaborationGroup record in your unit test?
    – sfdcfox
    Feb 21, 2016 at 4:43
  • Yes, to no avail. Feb 21, 2016 at 4:47
  • 2
    Personally, when I need to do unit test SOQL rigging, I set up my class as follows: public class X { @TestVisible static string query = 'select ... '; global Database.QueryLocator start(...) { return Database.getQueryLocator(query); }. Then, in the unit test, you can say "X c = new X(); x.query = 'select ... '; Database.executeBatch(c);` ... This lets you get 100% coverage and still pass unit tests.
    – sfdcfox
    Feb 21, 2016 at 4:51
  • I like it, I'll revise my code. Much cleaner that way. Thanks @sfdcfox! Feb 21, 2016 at 5:05

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .