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>');
}