Sub topic 9
Testing error paths and exceptions
Most tests check the happy path. Production failures usually happen on the other paths: blank input, a missing required field, a validation rule that rejects a record. This chapter shows how to test code that is supposed to fail, and how to avoid tests that pass whether or not the failure happens. It assumes you can write an @IsTest method, call Assert.areEqual, and read a DmlException.
Why error paths need their own tests
A method that throws on bad input makes a promise: callers get a specific exception with a useful message. If no test checks that promise, a later change can break it without anyone noticing. A negative test checks three things:
- The code fails when it should.
- It fails with the expected exception type and message.
- It leaves no unwanted changes behind.
The code under test for the first examples is a small service with two failure modes.
// DiscountException.cls
public class DiscountException extends Exception {}// DiscountService.cls
public class DiscountService {
public static Decimal apply(Decimal price, Decimal percent) {
if (price == null || price < 0) {
throw new IllegalArgumentException('Price must be zero or more');
}
if (percent == null || percent < 0 || percent > 100) {
throw new DiscountException('Percent must be between 0 and 100');
}
return price - (price * percent / 100);
}
}A custom exception class must extend Exception and its name must end in Exception. The body can be empty, because the base class supplies getMessage() and the constructors.
The try / fail / catch pattern
Apex has no assertThrows method, so you build one from try and catch. Put the call that should throw first, then Assert.fail, then a catch block for the exact exception type.
@IsTest
private class DiscountServiceTest {
@IsTest
static void negativePriceThrows() {
try {
DiscountService.apply(-5, 10);
Assert.fail('Expected IllegalArgumentException for a negative price');
} catch (IllegalArgumentException e) {
Assert.areEqual('Price must be zero or more', e.getMessage(), 'Unexpected exception message');
}
}
@IsTest
static void percentAboveHundredThrows() {
try {
DiscountService.apply(100, 150);
Assert.fail('Expected DiscountException for percent above 100');
} catch (DiscountException e) {
Assert.areEqual('Percent must be between 0 and 100', e.getMessage(), 'Unexpected exception message');
}
}
@IsTest
static void validInputReturnsDiscountedPrice() {
Decimal result = DiscountService.apply(200, 25);
Assert.areEqual(150, result, '25 percent off 200 should be 150');
}
}The flow has three outcomes, shown below.
Why Assert.fail is not swallowed
Assert.fail throws a System.AssertException. Your catch (IllegalArgumentException e) block does not match that type, so the exception leaves the test method and the test fails. This is why you catch the narrowest type you expect.
The catch (Exception e) trap
Catching the base Exception type breaks the pattern. The catch block now also catches the AssertException thrown by Assert.fail.
@IsTest
static void brokenNegativeTest() {
try {
DiscountService.apply(100, 10); // valid input, so nothing is thrown
Assert.fail('Expected an exception');
} catch (Exception e) {
Assert.isNotNull(e, 'An exception was thrown'); // passes: e is the AssertException
}
}This test passes even though the code under test threw nothing. If you must catch Exception, assert on the type and message too. A mismatch then fails the test:
@IsTest
static void typeIsCheckedWhenCatchingBase() {
try {
DiscountService.apply(-1, 10);
Assert.fail('Expected an exception');
} catch (Exception e) {
Assert.isInstanceOfType(e, IllegalArgumentException.class, 'Wrong exception type: ' + e.getTypeName());
}
}Testing DML failures
Platform errors arrive as a DmlException. It can describe several failed records, so it exposes indexed accessors:
| Method | Returns |
|---|---|
| `getNumDml()` | Number of records that failed |
| `getDmlType(i)` | The `StatusCode` for failure `i`, such as `REQUIRED_FIELD_MISSING` |
| `getDmlFieldNames(i)` | Field names involved in failure `i` |
| `getDmlMessage(i)` | The message for failure `i` |
Assert on the status code, not on the full message text. Messages can change with language settings and platform releases, while StatusCode values are stable.
@IsTest
static void insertWithoutNameFails() {
try {
insert new Account();
Assert.fail('Expected DmlException for a missing Name');
} catch (DmlException e) {
Assert.areEqual(1, e.getNumDml(), 'One record should fail');
Assert.areEqual(StatusCode.REQUIRED_FIELD_MISSING, e.getDmlType(0), 'Unexpected status code');
Assert.isTrue(e.getDmlFieldNames(0).contains('Name'), 'The Name field should be reported');
}
}The same approach works for failures you create yourself. A trigger that calls addError('Close date is required'), or a validation rule, surfaces as a DmlException when your test performs the DML. Read the text with e.getDmlMessage(0), or use e.getMessage() and check that it contains the text.
Partial success with Database methods
Plain insert is all or nothing. Database.insert(records, false) saves the valid records and reports the failures in a result list instead of throwing. A negative test then inspects the results, and a try block is the wrong tool.
@IsTest
static void partialInsertReportsFailureAndKeepsValidRecord() {
List<Account> accts = new List<Account>{
new Account(Name = 'Valid Account'),
new Account() // missing Name
};
List<Database.SaveResult> results = Database.insert(accts, false);
Assert.isTrue(results[0].isSuccess(), 'The valid record should save');
Assert.isFalse(results[1].isSuccess(), 'The record without a Name should fail');
Database.Error err = results[1].getErrors()[0];
Assert.areEqual(StatusCode.REQUIRED_FIELD_MISSING, err.getStatusCode(), 'Unexpected status code');
Integer saved = [SELECT COUNT() FROM Account];
Assert.areEqual(1, saved, 'Only the valid record should be in the database');
}The final query matters. isSuccess() tells you what the platform reported, and the query confirms what was stored.
Checking that nothing changed
A failure should often leave the data untouched. Catching an exception inside a test does not roll back DML that ran before the throw. Asserting only on the exception can hide a half-finished update, so re-query and compare after the catch block.
@IsTest
static void failedUpdateLeavesRatingUnchanged() {
Account acct = new Account(Name = 'Acme', Rating = 'Cold');
insert acct;
try {
AccountService.flagLargeAccounts(null);
Assert.fail('Expected an exception for a null list');
} catch (NullPointerException e) {
Assert.isNotNull(e.getMessage(), 'The exception should carry a message');
}
Account reloaded = [SELECT Rating FROM Account WHERE Id = :acct.Id];
Assert.areEqual('Cold', reloaded.Rating, 'Rating should not change after a failure');
}This test uses AccountService from the bulk-testing chapter. Looping over a null list throws a NullPointerException, so this test also documents what that method does today. If you later add an explicit argument check, update the test to expect your new exception.
AuraHandledException messages
Controllers for Lightning components often throw AuraHandledException. By default, its getMessage() returns the generic text Script-thrown exception, even when you passed a message to the constructor. Call setMessage in the code under test so that callers, and tests, can read the text.
public with sharing class ProfileController {
@AuraEnabled
public static String load(Id recordId) {
if (recordId == null) {
AuraHandledException ex = new AuraHandledException('Record Id is required');
ex.setMessage('Record Id is required');
throw ex;
}
return 'loaded';
}
}@IsTest
private class ProfileControllerTest {
@IsTest
static void nullIdThrowsReadableMessage() {
try {
ProfileController.load(null);
Assert.fail('Expected AuraHandledException for a null Id');
} catch (AuraHandledException e) {
Assert.areEqual('Record Id is required', e.getMessage(), 'Unexpected message');
}
}
}Errors in asynchronous code
An exception thrown inside a Queueable, batch, or future method does not reach your test method. It surfaces when Test.stopTest() runs the job, and an unhandled one fails the test at that point. To test a failure path in async code, make the job catch the error and record the outcome in a field or custom object. Then assert on that record after Test.stopTest().
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Missing `Assert.fail` after the call | Test passes when nothing is thrown | Always put `Assert.fail` right after the call that should throw |
| `catch (Exception e)` with a weak assertion | `AssertException` is swallowed | Catch the specific type, or assert on type and message |
| Asserting the full platform message | Test breaks when wording changes | Assert on `StatusCode` or field names |
| Several failing calls in one `try` block | A later call never runs, and you cannot tell which one threw | One negative scenario per test method |
| No check on data after the failure | Partial changes go unnoticed | Re-query and assert the state |
Exercise
A teammate writes this test for a method that should throw DiscountException when percent is 101. It passes, but the method was changed and no longer throws. Why does the test still pass, and how do you fix it?
try {
DiscountService.apply(100, 101);
Assert.fail('Expected DiscountException');
} catch (Exception e) {
Assert.isNotNull(e.getMessage(), 'Message should exist');
}
Show answer
Assert.fail throws an AssertException, which is an Exception, so the catch (Exception e) block catches it and getMessage() is not null. Nothing fails. Fix it by catching DiscountException specifically and asserting on the message, for example Assert.areEqual('Percent must be between 0 and 100', e.getMessage(), 'Unexpected message'). The AssertException then passes through the catch block and fails the test.
Exercise
You call Database.insert(accts, false) with 3 accounts, one of them without a Name. Name two assertions that confirm both the error and the saved data.
Show answer
First, check the failing record's result: Assert.isFalse(results[2].isSuccess(), ...), and optionally Assert.areEqual(StatusCode.REQUIRED_FIELD_MISSING, results[2].getErrors()[0].getStatusCode(), ...). Second, query the database and assert that exactly 2 accounts were saved, for example Assert.areEqual(2, [SELECT COUNT() FROM Account], ...). The result objects show what the platform reported, and the query shows what was stored.