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
Piotr B. KożuchowskiPiotr B. Kożuchowski 

How can I insert test user for testing batch callout?

Hi All

When I create test user in unit tests and execute a batch that does callout, it fails with "Uncommited work pending" exception.
It happens only when I try to insert User, if I comment out "insert user" and leave any other SObject insertions, it will work just fine.

Do you know how can I get around this?
 

@TestSetup
    static void testSetup() {
        Profile p = [SELECT Id FROM Profile WHERE Name = 'System Administrator'];
        User usr = new User(
                FirstName = 'Test',
                LastName = 'User',
                Email = 'example@dev.sandbox.com',
                Username = 'example@dev.sandbox.com',
                ProfileId = p.Id,
                Alias = 'example',
                CommunityNickname = 'example',
                TimeZoneSidKey = 'GMT',
                LocaleSidKey = 'nl_NL',
                EmailEncodingKey = 'UTF-8',
                LanguageLocaleKey = 'en_US'
        );
        insert usr;
        insert new Account(Name = 'Test');
    }

    @IsTest
    static void testBehavior() {
        Test.startTest();
        Test.setMock(HttpCalloutMock.class, new TestMock());
        Database.executeBatch(new POC_BatchCallout());
        Test.stopTest();
    }
The batch in this example does nothing else, but callout.

Kind Regards
 
Raj VakatiRaj Vakati
Refer this link 

https://salesforce.stackexchange.com/questions/11606/testing-batch-job-with-http-callouts
You need to do it like this 
 
HTTPResponse resp;
if(!Test.isRunningTest())
{
     resp = http.send(req);
}
else
{
     resp = MockApiCalls.WebserviceExpectedResponse();
}

 
Piotr B. KożuchowskiPiotr B. Kożuchowski
Sorry Raj, your answer is correct, but I've asked wrong question ^^

I'm not looking for a workaround, I want to know why inserting user makes callout fail whereas everything works fine with DML on any other object. This looks like an apex bug to me.
Raj VakatiRaj Vakati
This is not a bug but limitation i can say 
Piotr B. KożuchowskiPiotr B. Kożuchowski
Limitation from separating unit tests from environment data, that's for sure :)