Loading

System.assertEquals does not return expected value in Test Methods

Veröffentlichungsdatum: Oct 13, 2022
Beschreibung
System.assertEquals does not return the expected value in Test Class.
When you perform an insert and then immediately call System.assertEquals, the test fails. This is because 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
Lösung
Query the account record before executing 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. 

 
Nummer des Knowledge-Artikels

000383662

 
Laden
Salesforce Help | Article