Sub topic 15
Testing that code throws the right exception
This chapter assumes you can write basic Apex test classes with @IsTest, and that you have read the earlier chapters on try/catch, custom exceptions, and DML errors. Here you will learn how to prove that your code fails in the way you designed.
Why test the failure path
Most test classes check the happy path. Error handling is also behavior, and it breaks quietly. A refactor can change an exception type, drop a cause, or let a bad value through without any error. A test that expects an exception fails when that happens.
Apex has no annotation like JUnit's expected. You test exceptions by hand with try and catch. The pattern is simple, but it has one trap, covered below.
The basic pattern
@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'));
}
}
}Each part has a job:
- The call that should fail goes inside
try. Assert.failon the next line runs only if the call did not throw. It raises anAssertException, which fails the test.- The
catchnames the exact exception type you expect. - Assertions inside the
catchcheck the message, cause, or other details.
The flow looks like this.
The trap: catching too broadly
Assert.fail throws an AssertException, and AssertException extends Exception. Suppose you write this:
try {
InvoiceService.applyDiscount(100, 150);
Assert.fail('Expected an exception');
} catch (Exception e) {
// swallows the AssertException too
}If no exception is thrown, Assert.fail raises an AssertException. The generic catch (Exception e) then catches it, and the test passes when it should fail. This is why you catch the specific type. If you must catch Exception, use a flag instead of Assert.fail:
@IsTest
static void rejectsInvalidDiscountWithFlag() {
Boolean thrown = false;
try {
InvoiceService.applyDiscount(100, 150);
} catch (Exception e) {
thrown = true;
Assert.areEqual('InvoiceService.InvoiceException', e.getTypeName());
}
Assert.isTrue(thrown, 'Expected an exception to be thrown');
}The assertion after the try block sits outside the catch, so nothing can swallow it. getTypeName returns the fully qualified name, so an inner class appears as InvoiceService.InvoiceException.
Test the message and the type
An exception type alone is a weak check. Many different problems can throw a DmlException. Asserting on the message, or on a stable part of it, confirms that the failure came from the branch you meant to test.
- Use
containsinstead ofareEqualfor messages that include runtime values or system text. System messages can change between releases. - Prefer checking a status code or field name when the platform gives you one.
- Keep your own messages stable, since your tests depend on them.
Testing DML failures
Make DML fail by sending data that breaks a rule. A missing required field is the easiest way. The DmlException methods give you structured detail:
@IsTest
private class AccountDmlTest {
@IsTest
static void missingNameReportsRequiredField() {
try {
insert new Account();
Assert.fail('Expected a DmlException');
} catch (DmlException e) {
Assert.areEqual(1, e.getNumDml());
Assert.areEqual('REQUIRED_FIELD_MISSING', e.getDmlStatusCode(0));
Assert.isTrue(e.getDmlFieldNames(0).contains('Name'));
}
}
}getDmlStatusCode returns the status code as a string, and getDmlFieldNames returns a list of field names. Both take the index of the failed record.
Testing partial success
With Database.insert(records, false) nothing is thrown. The failure lives in the SaveResult list, so you assert on results instead of catching:
@IsTest
static void partialInsertSavesValidRecords() {
List<Account> accts = new List<Account>{ new Account(Name = 'Valid'), new Account() };
List<Database.SaveResult> results = Database.insert(accts, false);
Assert.isTrue(results[0].isSuccess());
Assert.isFalse(results[1].isSuccess());
Assert.areEqual(
StatusCode.REQUIRED_FIELD_MISSING,
results[1].getErrors()[0].getStatusCode()
);
Assert.areEqual(1, [SELECT COUNT() FROM Account WHERE Name = 'Valid']);
}The last line also confirms that the valid record was saved, which is the point of partial success.
Testing wrapped exceptions and causes
When a service wraps a low-level exception, test both layers. Callers rely on the wrapper type and on getCause for diagnosis. Using the AccountService from the chaining chapter:
@IsTest
static void wrapsDmlExceptionWithCause() {
try {
AccountService.create(new Account());
Assert.fail('Expected AccountServiceException');
} catch (AccountService.AccountServiceException e) {
Assert.areEqual('Could not create account', e.getMessage());
Assert.isNotNull(e.getCause(), 'Cause should be preserved');
Assert.isInstanceOfType(e.getCause(), DmlException.class, 'Cause should be a DmlException');
}
}If someone later removes the cause argument when wrapping, this test fails.
Testing rollback
A rollback test must show that data is gone, not only that an exception occurred. Here is a service that wraps the savepoint pattern:
public class OnboardingService {
public static void createParentWithContact() {
Savepoint sp = Database.setSavepoint();
try {
Account acc = new Account(Name = 'Parent');
insert acc;
insert new Contact(AccountId = acc.Id); // LastName is missing, so this fails
} catch (DmlException e) {
Database.rollback(sp);
throw e;
}
}
}@IsTest
private class OnboardingServiceTest {
@IsTest
static void rollsBackParentWhenContactFails() {
try {
OnboardingService.createParentWithContact();
Assert.fail('Expected a DmlException');
} catch (DmlException e) {
Assert.areEqual(
0,
[SELECT COUNT() FROM Account WHERE Name = 'Parent'],
'Parent account should have been rolled back'
);
}
}
}The query runs after the rollback and proves it worked. Without that check, a missing Database.rollback call would go unnoticed.
Testing AuraHandledException
AuraHandledException has a quirk. If you build it with a message but never call setMessage, getMessage() returns the generic text Script-thrown exception in Apex. The controller from the earlier chapter calls setMessage, so a test can read the real text:
@IsTest
private class AccountControllerTest {
@IsTest
static void returnsReadableErrorToLightning() {
try {
AccountController.saveAccount(new Account());
Assert.fail('Expected AuraHandledException');
} catch (AuraHandledException e) {
Assert.isTrue(e.getMessage().contains('REQUIRED_FIELD_MISSING'));
}
}
}What you cannot test this way
- Uncatchable limit exceptions. Hitting a governor limit ends the transaction, and no
catchcan intercept it. Test the logic that avoids the limit instead, for example by running a bulk of 200 or more records through your code and checking that it completes. - Asynchronous failures. A
Queueableor batch job runs whenTest.stopTest()is called, not at the point where you enqueue it. Keep the real logic in a plain method that you call directly, and test that method's exceptions as shown above.
Summary of techniques
| Situation | What to assert |
|---|---|
| Custom exception thrown | Exact type in `catch`, then message with `contains` |
| Wrapped exception | Wrapper type, `getCause` is not null, cause type |
| `DmlException` | `getNumDml`, `getDmlStatusCode`, `getDmlFieldNames` |
| `Database.insert(..., false)` | `isSuccess`, `getErrors`, records actually saved |
| Rollback | Query shows the earlier DML is gone |
| Broad `catch (Exception)` | Use a `thrown` flag, not `Assert.fail` |
Exercise
A teammate writes a test with try { service.run(); Assert.fail('no exception'); } catch (Exception e) { Assert.isTrue(true); }. The run method has a bug and never throws. Does the test pass or fail, and how would you fix it?
Show answer
It passes, which is wrong. Assert.fail throws an AssertException, and catch (Exception e) catches it. Fix it by catching the specific expected exception type, so the AssertException escapes and fails the test. Alternatively, set a thrown flag in the catch and call Assert.isTrue(thrown) after the try block.
Exercise
You wrote a service method that wraps a DmlException in your own exception. List the three things a thorough test should assert.
Show answer
The wrapper exception type (by catching it specifically), the message you set, and that getCause is not null and is an instance of DmlException.
Exercise
Why does a rollback test need a SOQL query after the exception, instead of only catching the exception?
Show answer
Catching the exception only shows that something failed. The query shows that the earlier DML was actually undone. Without it, the test would still pass if the Database.rollback call were removed.