Sub topic 9
Testing error paths and exceptions
This chapter assumes you can write a basic @IsTest method, know the common Assert methods, and can read a try/catch block in Apex. Code that works on good input is only half of what a test should prove. The other half is that the code fails the way you designed it to fail.
Why error paths need their own tests
Error paths are easy to skip. A method that throws on bad input may still show high code coverage if other tests call it with valid data. The throw line itself never runs in those tests, and nothing checks that the right exception, with the right message, reaches the caller.
A negative test calls the code with input that should be rejected, then checks that the rejection happened.
The try/catch/Assert.fail pattern
Apex has no assertThrows method. The standard pattern uses three parts:
- Call the code inside a
tryblock. - Put
Assert.failon the line right after the call. It runs only if no exception was thrown, so the test fails with your message. - Catch the specific exception type and assert on its details.
public class StringUtil {
public static String initials(String fullName) {
if (String.isBlank(fullName)) {
throw new IllegalArgumentException('Name is required');
}
String result = '';
for (String part : fullName.trim().split(' ')) {
if (String.isNotBlank(part)) {
result += part.substring(0, 1).toUpperCase();
}
}
return result;
}
}
@IsTest
private class StringUtilErrorTest {
@IsTest
static void blankNameThrows() {
try {
StringUtil.initials(' ');
Assert.fail('Expected IllegalArgumentException for a blank name');
} catch (IllegalArgumentException e) {
Assert.areEqual('Name is required', e.getMessage(), 'Unexpected exception message');
}
}
}Assert.fail throws an AssertException. The catch block names IllegalArgumentException, so it does not catch the AssertException. The failure reaches the test runner as intended. If you wrote catch (Exception e), the catch block would swallow the AssertException and the test would pass when it should fail.
flowchart TD
A[Call method with bad input] --> B{Exception thrown?}
B -- No --> C[Assert.fail runs, test fails]
B -- Yes --> D{Matches catch type?}
D -- No --> E[Exception escapes, test fails]
D -- Yes --> F[Assert on message or type]The diagram above must use the required fence, so here it is in the required form.
Common mistakes
- Catching
ExceptionaroundAssert.fail. As described above, this hides the failure. Catch the specific type the code should throw. - Skipping the message assertion. A test that only checks the type passes even if the message is wrong. Assert on
e.getMessage()when the message matters to callers. - Putting setup code inside the
try. If setup throws the same exception type, the test passes for the wrong reason. Build your data before thetry, and keep only the call under test inside it. - Testing several failures in one method. After the first catch, the later calls still need their own
tryblocks. Separate methods give clearer failure reports.
Testing DML failures
Errors also come from the database, such as a missing required field. Use Database.insert with allOrNone set to false when you want to inspect the failure without an exception. Use a plain insert inside the try block when you expect a DmlException.
@IsTest
private class AccountDmlErrorTest {
@IsTest
static void missingNameFailsInsert() {
Account acct = new Account();
try {
insert acct;
Assert.fail('Expected DmlException for missing Name');
} catch (DmlException e) {
Assert.isTrue(
e.getMessage().contains('REQUIRED_FIELD_MISSING'),
'Message should name the missing field error: ' + e.getMessage()
);
Assert.areEqual(StatusCode.REQUIRED_FIELD_MISSING, e.getDmlType(0), 'Unexpected DML status code');
}
}
@IsTest
static void partialSaveReportsError() {
Database.SaveResult result = Database.insert(new Account(), false);
Assert.isFalse(result.isSuccess(), 'Insert without a Name should fail');
Assert.areEqual(1, result.getErrors().size(), 'Expected exactly one error');
}
}Checking getDmlType(0) is more stable than matching message text, because the status code does not change with wording.
Exercise
A test calls a method that should throw a CustomException, but the method was changed and no longer throws. The test wraps the call in try, puts Assert.fail after it, and uses catch (Exception e). Does the test fail? Why?
Show answer
No. Assert.fail throws an AssertException, which is a subclass of Exception, so the catch block catches it and the test passes. Catch the specific CustomException type so the AssertException escapes and fails the test.