Menu
subscribe our youtube channel popup

Improve Apex Testing with New SObject Error Methods

Basically, this Winter 21 update for improve test class error methods. Salesforce introduced two new methods SObject.hasErrors() and SObject.getErrors(). With this method, 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.

New SObject Error Methods

There are three new subject 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

Apex Hours
Apex Hours

Salesforce Apex Hours is a program of the community, for the community, and led by the community. It is a space where Salesforce experts across the globe share their expertise in various arenas with an intent to help the Ohana thrive! Join us and learn about the apex hours team.

Articles: 427

Leave a Reply

Your email address will not be published. Required fields are marked *