Sub topic 3
Testing Error Paths and Exceptions
Assume you know Apex classes, DML, SOQL, and governor limits. Reliable tests check both successful results and controlled failures.
Testing Error Paths and Exceptions
A negative test checks what happens when input is invalid. Catch the expected exception, then verify its message. Put Assert.fail immediately after the call. It runs only when the exception was not thrown.
@IsTest
static void blankNameThrows() {
try {
StringUtil.initials(' ');
Assert.fail('Expected an exception for a blank name');
} catch (IllegalArgumentException e) {
Assert.areEqual(
'Name is required',
e.getMessage(),
'The exception message should explain the error'
);
}
}Catch the specific exception your production code documents. A test that catches Exception can hide an unexpected failure.
Testing as a Specific User
System.runAs executes a block with a chosen user context. Use it to test sharing behavior or logic that depends on UserInfo. It does not test field-level or object-level permissions.
System.runAs(testUser) {
Assert.areEqual(
testUser.Id,
UserInfo.getUserId(),
'The service should run as the selected user'
);
}Create the test user with a unique username. Keep user-context tests focused on behavior that changes for that user.
Mocking HTTP Callouts
A test cannot make a real HTTP callout. HttpCalloutMock returns a controlled response instead.
Test.setMock(HttpCalloutMock.class, new WeatherMock());
Test.startTest();
HttpResponse response = new Http().send(request);
Test.stopTest();
Assert.areEqual(200, response.getStatusCode(), 'The service should receive success');Test success, error status codes, malformed bodies, and timeout behavior when the production code handles them.
Testing Queueable, Batch, and Future Code
Call asynchronous code between Test.startTest() and Test.stopTest(). Salesforce runs queued work when stopTest() completes.
sequenceDiagram
participant T as Test
participant A as Async Apex
participant D as Database
T->>T: Test.startTest()
T->>A: Enqueue or invoke work
T->>T: Test.stopTest()
A->>D: Save result
T->>D: Query and assertQuery the database after stopTest(). Assert the saved result, not only that the job was submitted.
Habits of Reliable Tests
- Use isolated test data and meaningful failure messages.
- Test one behavior per method.
- Include zero, one, many, and invalid inputs.
- Test bulk inputs without querying or updating inside loops.
- Treat code coverage as a minimum signal. Coverage does not prove correctness.
Exercise
Where should you place assertions for an asynchronous database update?
Show answer
After Test.stopTest(), then query the saved records and assert their values.