Sub topic 3
Testing Invalid Input and Expected Exceptions
Assume you know basic Apex classes, triggers, SOQL, DML, and governor limits. A meaningful test checks what the code does, including how it fails.
Test invalid input
Use try and catch when the method should throw an exception. Assert.fail makes the test fail if no exception occurs.
@isTest
private class DiscountCalculatorTest {
@isTest
static void rejectsPercentOutOfRange() {
try {
DiscountCalculator.apply(100, 150);
Assert.fail('Expected an IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.isTrue(
e.getMessage().contains('between 0 and 100')
);
}
}
}Test boundary values and each important failure branch. Checking the exception message can reveal which validation failed.
Test user context
System.runAs runs test code as a selected User. Use it to verify sharing-dependent behavior.
System.runAs(testUser) {
List<Account> visible = AccountService.visibleAccounts();
Assert.areEqual(1, visible.size());
}Create testUser in test data. runAs tests record sharing, but it does not enforce object permissions or field-level security.
Mock HTTP callouts
A test cannot make a real HTTP callout. HttpCalloutMock supplies a controlled response.
private class RateMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest request) {
HttpResponse response = new HttpResponse();
response.setStatusCode(200);
response.setBody('{"rate":12.5}');
return response;
}
}
Test.setMock(HttpCalloutMock.class, new RateMock());
Test.startTest();
Decimal rate = ShippingClient.getRate();
Test.stopTest();
Assert.areEqual(12.5, rate);Also test error responses such as status 500.
Test asynchronous Apex
Place asynchronous work between Test.startTest() and Test.stopTest(). Salesforce runs queued work when stopTest() executes. Use this pattern for Queueable, Batch, and future methods, then query records and assert their final state.
diagram TD
A[Arrange test data] --> B[Test.startTest]
B --> C[Enqueue or call async code]
C --> D[Test.stopTest]
D --> E[Assert committed results]caption: Testing asynchronous Apex alt: A flow from arranging data through startTest, asynchronous execution, stopTest, and result assertions
Review coverage and maintain strategy
Run tests in Setup under Apex Test Execution, or use the Salesforce CLI:
sf apex run test --tests DiscountCalculatorTest --code-coverage --result-format human --wait 10Coverage counts executed lines, not verified behavior. Keep tests isolated from organization data, use factories or @TestSetup, cover happy, bulk, permission, and failure paths, and assert business outcomes. Add a test when a bug is fixed.
Exercise
What must a test do when it expects a method to throw an exception?
Show answer
Call Assert.fail immediately after the method call, then catch the expected exception and assert its relevant details.