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
DaveLDaveL 

Test.startTest no longer allows test data setup prior to Http Mock callout?

Trying to test HTTP callouts, after setting up test data.  Error is "System.CalloutException: You have uncommitted work pending."  I thought that wrapping the test in Test.startTest() and Test.stopTest() would allow one to setup test data, and then exercise the callout. (based on many previous answers to this sort of question, and prev. experience).  Has this changed with Spring 15 or have I forgotten some fundamental thing?
Can anyone replicate this issue (or tell me what dumb thing I'm (not)doing) ?
Code I'm using to figure this out
@isTest
public class TestMockUnit {
	
	    static testMethod void myUnitTest() {
            // setup theoretical test data (never mind that I don't actually use it, 
            //       this is just to prove that the DML activity survives
            //       across a Test.startTest() )
	        Contact c = new Contact(FirstName = 'Test',  LastName = 'MockCall', BirthDate = Date.valueOf('2000-01-01'), cv__Gender__c = 'Male');
	        insert c;
	        
	    Test.startTest();
	        Test.setMock(HttpCalloutMock.class, new TestMockClass());
                TestMockCallout.doCallout();
            Test.stopTest(); 
   
	    }
        
}

@isTest
global class TestMockClass implements HttpCalloutMock  {

    global HTTPResponse respond(HTTPRequest req) {
        HttpResponse res = new HttpResponse();
        res.setStatusCode(200);
        return res;
    }
}

public class TestMockCallout {
    // my "production" callout.
    public static void doCallout(){
    	    HttpResponse res;
            Http h = new Http();
            HttpRequest req = new HttpRequest();
            req.setHeader('Content-type', 'application/json');
            req.setEndpoint('http://www.google.com');
            req.setMethod('GET');
            res = h.send(req);
    }
}

 
DaveLDaveL
Well it turns out its related to known issue https://success.salesforce.com/issues_view?id=a1p300000008XHBAA2.   My contact insert has a workflow attached to it that has an Email-Alert configured.  Deleting the Email Alert (in my sandbox) allows the unit test to run correctly.  Fortunately for my particular test, I can test w/o actually having to insert the test data...but hey it was cool to spend 4 hrs figuring this out.  :)