Uncommitted Work Error with MultiStaticResourceCalloutMock

I am using the MultiStaticResourceCalloutMock to test a callout to Twitter. I am using the Test.Start/Stop to wrap the test.mock implementation which has previously fixed the issues we all had with using DML and Mock. Any ideas why the code below is causing the error again?

private static void testTwitterBatch () {

//Setup Custom Settings
social_media_settings__c sms = new social_media_settings__c(Name = 'Twitter');
sms.URL__c = 'https://api.twitter.com/1.1/users/lookup.json?screen_name=';
sms.API_Key__c = 'KEYPUBLIC';
sms.API_Secret_Key__c = 'KEYPRIVATE';
insert sms;

Contact c = new Contact (
LastName = 'Test Twitter 1', 
Twitter_Username__c = 'britishboyindc');
insert c; 

Test.starttest();

MultiStaticResourceCalloutMock multimock = new MultiStaticResourceCalloutMock();
multimock.setStaticResource('https://api.twitter.com/oauth2/token', 'TwitterBearerResponse');
multimock.setStaticResource('https://api.twitter.com/1.1/users/lookup.json?screen_name=britishboyindc', 'TwitterResultsResponse');
multimock.setStatusCode(200);
multimock.setHeader('Content-Type', 'application/json');


        // Set the mock callout mode
        Test.setMock(HttpCalloutMock.class, multimock);

        TwitterStatsUpdate_batch tb = new TwitterStatsUpdate_batch();
        tb.query = 'Select Id, Twitter_Username__c, Twitter_Followers__c from Contact';
        database.executebatch(tb,50);

Test.stoptest();   

Answer

I’ve never found testing batches to be particularly friendly. I often fake the asynchronous process by just calling the relevant methods directly which helps avoids issues with StartTest() and StopTest() and data not being what you expect.

Maybe trying something like this will fix your issue?

TwitterStatsUpdate_batch tb = new TwitterStatsUpdate_batch();
tb.query = 'Select Id, Twitter_Username__c, Twitter_Followers__c from Contact';
tb.execute(null, tb.start(null));

Attribution
Source : Link , Question Author : BritishBoyinDC , Answer Author : Matt Lacey

Leave a Comment