[SalesForce] Testing a scheduled class

I have two methods in a scheduled class. Both resemble the code below. I'm getting the following error when I call the second version.

System.AsyncException: The Apex job named "My batch Job" is already
scheduled for execution.

I thought scheduled classes ran immediately when being tested? I can get around the problem by commenting out one version of "ScheduleMe"; it's only used for testing. I'd like to know if there's a way for me to successfully test both of the scheduling functions.

global static String scheduleMe() {
    AutoChatter SC = new AutoChatter(); 
    return System.schedule('Autochatter-Notification Checker', schedmidnight, SC);
}

Here's the test class:

@IsTest public class AutoChatter_test {
static testMethod void AutoChatter_test(){        

    Test.startTest();       
    AutoChatter.scheduleMe5ahead();        
    Test.stopTest();        
}

static testMethod void AutoChatter_test2(){                
    Test.startTest();
    AutoChatter.scheduleMe();        
    Test.stopTest();        
}

Best Answer

I've run into this before. I had written the scheduled class and had already run the ScheduleMe method before running my tests, so it refused to schedule again on top of the existing schedule. All I did was delete the scheduled job in my Sandbox before running the tests. You can still run both ScheduleMe methods in production once you've deployed the class.

Or maybe are both methods trying to schedule the job under the same name?

Related Topic