Sub topic 10
Testing invalid input and expected exceptions
This chapter assumes you can read basic Apex (classes, SOQL, DML) and have written a test method with @isTest and the Assert class. It builds on the DiscountCalculator class from earlier chapters.
A happy-path test shows that code works when everything goes right. Production data is rarely that tidy. Users leave fields blank, integrations send nulls, and validation rules reject records. A negative test supplies bad input on purpose and asserts that the code fails in the way you designed.
Why failure paths need their own tests
Failure branches are real code. In DiscountCalculator, the two throw statements make up a large share of the method. If no test reaches them, those lines count as uncovered. A test that reaches them but never checks the outcome has the same weakness as the WeakDiscountCalculatorTest from the coverage-versus-quality chapter.
A negative test should check three things:
- The code fails. An exception is thrown, or an error result is returned.
- The failure is the right one. It has the expected type and a meaningful message or status code.
- The failure leaves no side effects, such as half-saved records.
The try, fail, catch pattern
The basic pattern has three parts:
- The call that should fail goes inside a
tryblock. Assert.failcomes directly after that call. It runs only if the call did not throw.- A
catchblock for the specific exception type asserts on the details.
@isTest
private class DiscountCalculatorNegativeTest {
@isTest
static void rejectsPercentAboveRange() {
try {
DiscountCalculator.apply(100, 150);
Assert.fail('Expected an IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.areEqual('percent must be between 0 and 100', e.getMessage(), 'Wrong message');
}
}
}Without Assert.fail, this test passes silently if the validation is removed. The try block finishes, no catch runs, and no assertion fails. This is the most common mistake in exception tests.
Catch the specific type
Assert.fail throws a System.AssertException. A broad catch (Exception e) will catch that exception and may mask the failure. The catch block then runs your assertions against the wrong exception. Often those assertions fail too, but the error message points at the wrong problem.
A helper that captures the exception
Apex has no lambdas, so you cannot write a general assertThrows helper. You can still avoid repeating the try block by writing a small helper for the method under test. It returns the exception it caught, or null if nothing was thrown.
@isTest
private class DiscountCalculatorValidationTest {
private static IllegalArgumentException tryApply(Decimal amount, Decimal percent) {
try {
DiscountCalculator.apply(amount, percent);
} catch (IllegalArgumentException e) {
return e;
}
return null;
}
@isTest
static void rejectsNullAmount() {
IllegalArgumentException e = tryApply(null, 10);
Assert.isNotNull(e, 'A null amount should be rejected');
Assert.areEqual('amount and percent are required', e.getMessage(), 'Wrong message');
}
@isTest
static void rejectsNullPercent() {
IllegalArgumentException e = tryApply(100, null);
Assert.isNotNull(e, 'A null percent should be rejected');
}
@isTest
static void rejectsPercentJustBelowZero() {
Assert.isNotNull(tryApply(100, -0.01), 'A percent below 0 should be rejected');
}
@isTest
static void rejectsPercentJustAboveHundred() {
Assert.isNotNull(tryApply(100, 100.01), 'A percent above 100 should be rejected');
}
@isTest
static void acceptsLowerBoundary() {
Assert.isNull(tryApply(100, 0), 'A percent of 0 is valid');
Assert.areEqual(100.00, DiscountCalculator.apply(100, 0), 'No discount at 0%');
}
@isTest
static void acceptsUpperBoundary() {
Assert.isNull(tryApply(100, 100), 'A percent of 100 is valid');
Assert.areEqual(0.00, DiscountCalculator.apply(100, 100), 'Full discount at 100%');
}
}The tests give each rule its own method with a descriptive name. When one fails, the method name tells you which rule broke.
Test the boundaries
Bugs cluster at the edges of a valid range. The calculator checks percent < 0 || percent > 100. If someone changes > to >=, a value of exactly 100 becomes invalid. Only a boundary test catches that.
| Input percent | Expected behavior | Why it matters |
|---|---|---|
| -0.01 | Rejected | Just below the lower limit |
| 0 | Accepted, no discount | Lower boundary is inclusive |
| 100 | Accepted, amount becomes 0 | Upper boundary is inclusive |
| 100.01 | Rejected | Just above the upper limit |
| null | Rejected | Missing value |
Writing these tests can also reveal missing rules. Try DiscountCalculator.apply(-50, 10). The class has no check for negative amounts, so it returns -45. That may be a bug or an accepted behavior. Either way, decide on it and write the test that records the decision.
Testing DML failures
Validation also happens in the database layer: required fields, validation rules, and addError calls in triggers. DML (data manipulation language, such as insert) can report failure in two ways.
Statement form: DmlException
With the plain insert statement, a failed save throws a DmlException. Inspect it for the row number, the status code and the failing fields. Prefer getDmlType(index), which returns a StatusCode, over matching message text. Message text can change between releases or translations.
@isTest
private class AccountDmlFailureTest {
@isTest
static void insertWithoutNameThrowsDmlException() {
try {
insert new Account();
Assert.fail('Expected a DmlException because Name is required');
} catch (DmlException e) {
Assert.areEqual(1, e.getNumDml(), 'One row should have failed');
Assert.areEqual(StatusCode.REQUIRED_FIELD_MISSING, e.getDmlType(0), 'Wrong status code');
Assert.isTrue(e.getDmlFieldNames(0).contains('Name'), 'Name should be the failing field');
}
}
@isTest
static void databaseInsertReportsErrorWithoutThrowing() {
Database.SaveResult result = Database.insert(new Account(), false);
Assert.isFalse(result.isSuccess(), 'The save should fail');
Database.Error error = result.getErrors()[0];
Assert.areEqual(StatusCode.REQUIRED_FIELD_MISSING, error.getStatusCode(), 'Wrong status code');
Assert.isTrue(error.getFields().contains('Name'), 'Name should be the failing field');
Assert.areEqual(0, [SELECT COUNT() FROM Account], 'No account should have been saved');
}
}Database method form: SaveResult
Database.insert(record, false) sets allOrNone to false. It does not throw. It returns a SaveResult for each record, and you assert on isSuccess() and getErrors(). This form is common in code that handles partial success, so test that code with a mix of valid and invalid records. Then assert on both the failed results and the records that did save.
Whichever form you use, finish with a query that proves the data state. With the default allOrNone behavior, a failed statement rolls back all of its rows, and a count of zero confirms that. A count of the successful rows confirms partial success.
Custom exceptions
Apex lets you define your own exceptions. A class that extends Exception must have a name ending in Exception.
public class DiscountException extends Exception {}Test a custom exception by catching that type, which is more precise than catching a built-in one. Assert on getMessage() only when the message is part of the contract, such as text a user sees. If callers branch on the failure type, assert on the type alone and leave the wording free to change.
One related gotcha: an AuraHandledException returns the generic message Script-thrown exception from getMessage() unless the code calls setMessage first. If your test asserts on the message, check the class under test sets it.
Common mistakes
- Omitting
Assert.fail, so the test passes when no exception is thrown. - Catching
Exceptionand asserting only that "something" was thrown. - Asserting on full message text that is not part of the contract, which makes the test brittle.
- Testing only one invalid value and skipping the boundaries.
- Forgetting to check that data was not changed after the failure.
- Testing an exception thrown inside
Test.startTest()andTest.stopTest()without placing the call that should throw inside thetryblock.
Exercise
A teammate writes this test for a method that should reject a null input: the method call sits inside a try block, the catch block is catch (IllegalArgumentException e) and it contains an assertion on the message. There is no Assert.fail after the call. A developer later deletes the null check from the method. What happens to the test, and how do you fix it?
Show answer
The test still passes. With the null check gone, the method no longer throws, so the catch block never runs and its assertion never executes. Nothing else in the test can fail. Add Assert.fail('Expected an IllegalArgumentException') on the line right after the call, inside the try block. With that line, a missing exception makes the test fail with a clear message.