Improve Apex Testing with New SObject Error Methods

Basically this Winter 21 update for improve test class error methods. Salesforce introduce two new methods SObject.hasErrors() and SObject.getErrors(). With this methods we can track errors without performing a DML operation to check the result for errors. Dynamically add errors to specific fields with new SObject.addError() overload methods.

There are really three new sObject methods to keep in mind here addError(),  getErrors()  and  hasErrors().

  1. SObject.addError() : Marks a trigger record with a custom error message and prevents any DML operation from occurring and Dynamically add errors to specific fields with new SObject.addError() overload methods.
  2. SObject.hasErrors() : Returns true if an SObject instance has associated errors. The error message can be associated to the SObject instance by using SObject.addError(), validation rules, or by other means.
  3. SObject.getErrors() : Returns a list of Database.Error objects for an SObject instance. If the SObject has no errors, an empty list is returned.

Check all other methods here.

Sample Code for SObject Error Method

@isTest
private class TestClassDemo {
 	@IsTest
    public static void testAddErroMethd() {
       //Baseline code sample for using addError, getErrors, together
       Account a = new Account();
       String msg = 'Demo = New error method in SObject';
       a.addError('Name', msg); 

       List<Database.Error> errors = a.getErrors(); // Get Error
       System.assertEquals(1, errors.size()); // Assert Result

       Database.Error error = errors.get(0);
       System.assertEquals(msg, error.getMessage()); // Validate message
       System.assertEquals(StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION, error.getStatusCode());

    }
}

If the SObject.addError() method has been called on an SObject instance, the SObject.hasErrors() method returns true. The SObject.getErrors() method returns a list of Database.Error objects that contain the errors encountered.

Further Learning

Leave a Comment