[SalesForce] Apex test code – system assert error

We have a custom object calls Account Contact Roles that assigns role to contact within an account. Once the record is inserted, there is a WF rule to update a field on the contact record calls "Roles__c" with following formula:

IF ( INCLUDES ( Roles__c , "Primary Contact" ), "Primary Contact: ",null ) & 

IF ( INCLUDES ( Roles__c , "Key Contact" ), "Key Contact: ",null ) &

IF ( INCLUDES ( Roles__c , "Billing Contact" ), "Billing Contact: ",null ) & 

IF ( INCLUDES ( Roles__c , "Sponsor Contact" ), "Sponsor Contact: ",null )

What we want to do is the clear out the field value when the Account Contact Roles record is deleted. The Apex code works in the Sandbox environment but need to test it before deploying. The test code is below:

@isTest

public class EmptyContactRole
{

 static testMethod void validateEmptyContactRole()

 {

  //insert records

    Account a1 = new Account(name = 'test1', Account_Type__c='non-Member', Industry='Banking');

    insert a1;

    Contact c1 = new Contact(lastname = 'test', Nickname__c='test');

    insert c1;

    Account_Contact_Role__c R = new Account_Contact_Role__c (Account__c= a1.id, Contact__c = c1.id, Roles__c = 'Primary Contact')

 //Insert insert R

 ;

c1 = [SELECT Id, Roles__c FROM Contact WHERE Id=:c1.Id];

System.assertEquals ('Primary Contact:',c1.Roles__c);

 //Delete Account Contact Role delete R

 delete R;

c1 = [SELECT Id, Roles__c FROM Contact WHERE Id=:c1.Id];

      System.assertEquals ('',c1.Roles__c);

}
}

Error Message System.AssertException: Assertion Failed: Expected: Primary Contact:, Actual: null
Stack Trace Class.EmptyContactRole.validateEmptyContactRole: line 15, column 1

Thanks for the help!

Best Answer

When testing workflow rules, you will need to wrap your insert DML in a startTest() and stopTest() method to ensure that the workflow rule has had time to finish processing prior to querying for the record. Since you can only have one startTest() and stopTest() method per unit test, you will likely need to breakout the delete scenario into a separate test method:

Test.startTest();
insert R;
Test.stopTest();

c1 = [SELECT Id, Roles__c FROM Contact WHERE Id=:c1.Id];
...