Sub topic 15
Testing that code throws the right exception
This chapter assumes you can write Apex classes and methods, run SOQL and DML, and know how custom exceptions are defined and thrown. Here you will learn how to write unit tests that prove your code fails the way you intend.
Why test the failure path
Tests that only cover the happy path leave your error handling unverified. An exception that never fires, or fires with the wrong type or message, is a bug that production users find first. A good exception test checks three things:
- An exception is thrown at all.
- It is the expected type.
- Its message (or other details) is correct.
The try, fail, catch pattern
The standard pattern calls the code inside try, then immediately calls Assert.fail on the next line. If the code throws nothing, Assert.fail raises an AssertException. The catch block only matches the expected type, so the AssertException escapes and the test fails. If the code throws the expected type, the catch block runs and checks the details.
@IsTest
private class InvoiceServiceTest {
@IsTest
static void rejectsInvalidDiscount() {
try {
InvoiceService.applyDiscount(100, 150);
Assert.fail('Expected InvoiceException was not thrown');
} catch (InvoiceService.InvoiceException e) {
Assert.isTrue(e.getMessage().contains('between 0 and 100'));
}
}
}Common mistakes
- Catching the generic
Exception. If you writecatch (Exception e)afterAssert.fail, theAssertExceptionis caught too, and the test passes when it should fail. Catch the specific type. - Skipping the message check. A test that only confirms the type will still pass if the wrong validation branch threw it.
- Putting setup code that can throw inside the
try. A failure in setup is then mistaken for the behavior under test. Do setup before thetry. - Leaving out
Assert.fail. Without it, the test passes silently when no exception occurs.
Testing DML failures
DML exceptions can be tested the same way. Use the DML-specific methods to check which field and message failed.
@IsTest
private class AccountDmlTest {
@IsTest
static void insertWithoutNameFails() {
try {
insert new Account();
Assert.fail('Expected DmlException was not thrown');
} catch (DmlException e) {
Assert.areEqual(1, e.getNumDml());
Assert.isTrue(e.getDmlFieldNames(0).contains('Name'));
Assert.areEqual('REQUIRED_FIELD_MISSING', e.getDmlStatusCode(0));
}
}
}When code uses Database.insert(records, false), nothing is thrown. Test the returned SaveResult list instead, and assert that isSuccess() is false for the failing record.
Checking that rollback happened
If your code rolls back to a savepoint after a failure, query afterward to confirm the data is gone. Assert on the record count, not only on the exception.
Choosing what to assert
| Check | Use it when |
|---|---|
| Exception type (the catch clause) | Always |
| `getMessage()` contains text | The message is part of the contract, such as an `AuraHandledException` shown to users |
| `getCause()` | Your code wraps a lower-level exception |
| `getDmlStatusCode(i)` | You need the exact validation failure |
Prefer contains over exact equality for messages that include dynamic values. That way small wording changes do not break the test.
Exercise
Why does the try, fail, catch pattern catch only the specific custom exception type instead of the generic Exception?
Show answer
Assert.fail throws an AssertException. A catch block for the generic Exception would also catch it, so the test would pass even when the expected exception was never thrown. Catching the specific type lets the AssertException escape and fail the test.
Exercise
A method uses Database.update(records, false) and reports failures through SaveResult. How do you test the failure case?
Show answer
No exception is thrown, so a try and catch does not apply. Call the method with an invalid record, then assert that the matching SaveResult has isSuccess() equal to false, and check getErrors() for the expected status code or message.