6

I am having a problem that I investigated down to this very simple minimalistic example that can be reproduced easily.

1) Create a workflow rule on the Account object that will send an email to the sales team when an account is created

2) Create a Unit Test like this:

static testMethod void Test_TestWS() {
     Account customer = new Account( Name = 'A' );
     INSERT customer;

      Test.startTest();
      Test.setMock(HttpCalloutMock.class, new UTest_Mock_HttpResponseGenerator());

       MyClass.CallWebService(customer.Id);
      Test.stopTest();
}

When executing the unit test I get this: System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out

What is the best practice to avoid this problem. I am following all guidelines in order to Mock my web service and to make sure that startTest is called AFTER my test data is inserted.

It looks like the workflow rule has some pending update in the DB that is not comitted on the startTest which causes the problem.

If I Deactivate the workflow rule, my test runs fine.

Thanks

Hugo

1

Here is a suggestion that I think might work. It is kind of weird, but bear with me.

So I will ask you to try the following:

public static Account customer { get; set; }

static
{
  //This will insert the record prior to the testMethod executing
  //Hence, this should fall outside of the testMethod's execution context
  //So, by the time it reaches the testMethod, the record will be available
  //AND the workflow will be complete.
  customer = new Account( Name = 'A' );
  INSERT customer;
}

static testMethod void Test_TestWS() 
{
    Test.startTest();
    Test.setMock(HttpCalloutMock.class, new UTest_Mock_HttpResponseGenerator());
    MyClass.CallWebService(customer.Id);
    Test.stopTest();
}

This is a possible workaround. Hopefully, this will get you over the hump or better yet, inspire some better answers.

  • Thanks for your help. Yes the account has been created. The workflow rule is actually an email that is sent when an account is created. It seems that because that email is not really sent, then the transaction is not finished. Maybe if I could just disable the workflow rule in my unit test? But I don't seem to be finding any way to do this. – Hugo Mar 10 '14 at 20:48
1

This is not an optimal solution, but create a checkbox field on your Account object. Add criteria to your Workflow Rule that requires that the checkbox field be unchecked in order to fire. Set that field to True whenever you're creating test data. If the workflow rule is not triggered, no callout will be made for the Email Alert.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.