Sub topic 10
Testing Invalid Input and Expected Exceptions
This chapter assumes you can write a basic @isTest class and use the Assert class. It covers negative testing: proving that your code rejects bad input the way you intended.
Why failure paths need their own tests
A happy-path test shows that valid input produces the right result. It says nothing about the if branches that guard against bad input. Those branches are often the code that protects your data. They are also the lines that stay uncovered when you only test the happy path.
Consider the validation in DiscountCalculator:
public with sharing class DiscountCalculator {
public static Decimal apply(Decimal amount, Decimal percent) {
if (amount == null || percent == null) {
throw new IllegalArgumentException('amount and percent are required');
}
if (percent < 0 || percent > 100) {
throw new IllegalArgumentException('percent must be between 0 and 100');
}
return amount - (amount * percent / 100);
}
}There are two throw statements here. A test that only calls apply(100, 10) leaves both unexecuted.
The try/catch pattern with Assert.fail
Apex has no built-in "expect this exception" annotation. The standard pattern wraps the call in try, calls Assert.fail on the line right after it, and checks the exception in catch.
@isTest
private class DiscountCalculatorNegativeTest {
@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'),
'Unexpected message: ' + e.getMessage()
);
}
}
@isTest
static void rejectsNullAmount() {
try {
DiscountCalculator.apply(null, 10);
Assert.fail('Expected an IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.isTrue(e.getMessage().contains('required'), 'Unexpected message: ' + e.getMessage());
}
}
}Assert.fail is what makes the test meaningful. Without it, a call that wrongly succeeds would skip the catch block, and the test would pass.
What to assert in the catch block
Checking only that some exception occurred is weak. Check at least one of these:
- The exception type, by catching the specific class.
- A distinctive part of the message.
- The side effects, such as confirming that no records were saved.
Compare the cost of each check:
| Check | Catches | Weakness |
|---|---|---|
| Exception type only | Wrong exception class | A different branch could throw the same type |
| Message contains text | Wrong branch triggered | Breaks if the wording is edited |
| No data changed | Partial saves after the error | Needs a query after the failure |
Testing DML and validation failures
For DML, you can use Database.insert(record, false) to get a result instead of an exception. Check isSuccess() and the error list.
@isTest
private class AccountValidationTest {
@isTest
static void insertWithoutNameFails() {
Database.SaveResult result = Database.insert(new Account(), false);
Assert.isFalse(result.isSuccess(), 'Insert without a Name should fail');
Assert.areEqual(
StatusCode.REQUIRED_FIELD_MISSING,
result.getErrors()[0].getStatusCode(),
'Name is a required field'
);
Assert.areEqual(0, [SELECT COUNT() FROM Account], 'Nothing should be saved');
}
}With a plain insert, the same failure raises a DmlException, and you would use the try/catch pattern instead.
Process of a negative test
Exercise
Why must Assert.fail come immediately after the call that should throw, and why should the catch block name a specific exception type?
Show answer
If the call does not throw, execution continues to Assert.fail, which fails the test. Without it, the test would pass silently because the catch block never runs. A specific exception type matters because Assert.fail throws an AssertException. A catch on the general Exception would catch it and hide the failure.
Exercise
Write a test that checks DiscountCalculator.apply(100, -5) is rejected.
Show answer
Use try, call DiscountCalculator.apply(100, -5), then Assert.fail('Expected an IllegalArgumentException'). In catch (IllegalArgumentException e), assert that e.getMessage() contains 'between 0 and 100'.