Understanding the addError() Method
The addError()
method in Salesforce is a powerful mechanism that lets developers add custom validation logic to records. It marks a trigger record with a custom error message, prevents DML operations, and can be applied to entire records or specific fields. Properly testing this functionality is crucial for maintaining reliable validation logic.
Causes of the addError() Testing Challenges
- Test execution continues even when errors occur, making it difficult to properly verify error messages.
- Default DML operations throw exceptions when validation fails, which can cause test failures rather than validating the behavior.
- Bulk testing scenarios require special consideration since addError can be applied to multiple records simultaneously.
How to Handle the addError() Testing
Method 1: Using Database.SaveResult
apex@isTest private class TestErrorValidation { @isTest static void testAddErrorMethod() { // Create test record that will trigger validation error Account acc = new Account(Name = 'INVALID_NAME'); // Use Database method with allOrNone=false to prevent test failure Database.SaveResult result = Database.insert(acc, false); // Verify the operation failed System.assertEquals(false, result.isSuccess()); // Verify the error message is correct System.assertEquals('Expected error message', result.getErrors()[0].getMessage()); } }
Method 2: Using try/catch Blocks
apex@isTest private class TestErrorValidation { @isTest static void testAddErrorMethod() { // Create test record that will trigger validation error Account acc = new Account(Name = 'INVALID_NAME'); try { // This should fail if addError() is triggered insert acc; // If we reach here, no error was thrown - test should fail System.assert(false, 'Expected an exception but none was thrown'); } catch(Exception e) { // Verify the error message contains the expected text System.assert(e.getMessage().contains('Expected error message')); } } }
Method 3: Using SObject Error Methods (Winter '21 and Later)
apex@isTest private class TestErrorValidation { @isTest static void testAddErrorMethod() { // Create test record Account acc = new Account(); // Add error to the record programmatically String errorMsg = 'This is the expected error message'; acc.addError('Name', errorMsg); // Verify errors exist System.assertEquals(true, acc.hasErrors()); // Get the errors and verify the message List<Database.Error> errors = acc.getErrors(); System.assertEquals(1, errors.size()); System.assertEquals(errorMsg, errors.get(0).getMessage()); } }
Conclusion
Testing addError()
validation in Salesforce requires using specific techniques to ensure your validation logic works correctly. By leveraging Database.SaveResult, try/catch blocks, or the newer SObject error methods, you can effectively verify error messages without causing your tests to fail. Remember to test both positive and negative scenarios and to make specific assertions about error messages.