1

I have a future method with some logic and I have written Test class for that.

  1. Calling future method inside test.startTest() and test.StopTest() in test class and asserting the values, in this case i'm getting 100% Coverage for the class which has future method.
  2. In this case i'm not including test.starttest() and test.stopTest(). here also i can assert the results and i'm getting 100% coverage for the class - Same Results In both cases

As per my understanding from the documentation, we should include all asynchronous calls between those two methods so that we can assert the results.

2

You need to ensure the asynchronous processing has complete in order to properly verify its behavior. If your tests are both passing, you likely are not correctly asserting that the @future method was executed. In other words, if you have not yet called stopTest, the underlying behavior you are testing has not yet been executed.

Let's consider a trivial example:

@future
public static void createChildContact(Id accountId, String lastName)
{
    insert new Contact(AccountId=accountId, LastName=lastName);
}

Now, this test will fail:

static testMethod void testCreateChildContact()
{
    final String LAST_NAME = 'Smith';
    Account parent = new Account(Name='ACME');
    insert parent;

    // omit Test.startTest();
        MyClass.createChildContact(parent.Id, LAST_NAME);
    // omit Test.stopTest();

    List<Contact> children = [SELECT AccountId, LastName FROM Contact];
    system.assertEquals(1, children.size(), 'A Contact should be created');
    system.assertEquals(parent.Id, children[0].AccountId, '<some_message>');
    system.assertEquals(LAST_NAME, children[0].LastName, '<some_message>');
}

While this test will succeed:

static testMethod void testCreateChildContact()
{
    final String LAST_NAME = 'Smith';
    Account parent = new Account(Name='ACME');
    insert parent;

    Test.startTest();
        MyClass.createChildContact(parent.Id, LAST_NAME);
    Test.stopTest();

    List<Contact> children = [SELECT AccountId, LastName FROM Contact];
    system.assertEquals(1, children.size(), 'A Contact should be created');
    system.assertEquals(parent.Id, children[0].AccountId, '<some_message>');
    system.assertEquals(LAST_NAME, children[0].LastName, '<some_message>');
}
1
  • I haven't tested properly before seeing this. Now i got what i wanted, Thanks @Adrian – RaJu Oct 1 '16 at 15:03

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.