Print this page

System.assertEquals does not return expected value in Test Methods

Knowledge Article Number 000193852
Description - System.assertEquals does not return the expected value in Test Class.
- When you perform an insert and then call System.assertEquals, the test fails. Since System.assertEquals does not check for the updated value by After Trigger.
- It is still checking against the variable stored in memory from before the DML operation.


Create an Account Trigger:
trigger NoOfEmployeesTrigger on Account (before insert, before update) {
 if(Trigger.isInsert) {  
 Account[] accs = Trigger.new; 
  for(Integer i=0; i<accs.size(); i++)  { 
     accs[i].NumberOfEmployees = 25;
  } 
 }
}


Create a Test class
@isTest 
public class AssertEqualsTest {
    static testMethod void validateAssertEquals() { 
       Account acc1 = new Account();
        acc1.name = 'Test class Acc';
        insert acc1;
//After Insert Trigger Updates Acc1 with NumberOfEmployees = 25
       System.assertEquals(25, acc1.NumberOfEmployees);     
    }
}
 

Execute the above Test class and it fails with below error.

​ Error Message: System.AssertException: Assertion Failed: Expected: 25, Actual: null Stack Trace    Class.AssertEqualsTest.validateAssertEquals: line 10, column 1

Resolution - Query the account record before we execute assert operation. Modify the test class to this
insert acc1;
 acc1 = [select NumberOfEmployees from Account where Id=:acc1.id];
 System.debug('Number after trigger: ' + acc1.NumberOfEmployees);
 System.assertEquals(25, acc1.NumberOfEmployees);


- This will return the required assertEquals results and hence the test will pass. 
The trigger updates the database record, not the 'in-memory' objects that were created to do the insert. 


Dev Doc: assertEquals()




promote demote