Sub topic 4
Choosing the right assertion method
This chapter assumes you can write a basic @IsTest method, run SOQL and DML, and read an Assert.areEqual call. Here you will learn which Assert method fits each check and how to write failure messages that help.
Why the method matters
Every Assert method fails the test when its condition is false. The difference is the failure output. Assert.areEqual(5, count, 'msg') reports both values. Assert.isTrue(count == 5, 'msg') reports only that a condition was false. Pick the most specific method so a failure tells you what went wrong without a debugger.
The common methods
| Method | Passes when | Typical use |
|---|---|---|
| `areEqual(expected, actual, msg)` | Values are equal | Field values, counts, strings |
| `areNotEqual(notExpected, actual, msg)` | Values differ | A value must change or stay distinct |
| `isTrue(condition, msg)` | Condition is true | Boolean results, `startsWith`, `contains` |
| `isFalse(condition, msg)` | Condition is false | Something must not hold |
| `isNull(value, msg)` | Value is null | An Id before insert |
| `isNotNull(value, msg)` | Value is not null | An Id after insert |
| `isInstanceOfType(instance, type, msg)` | Instance is of the type | Factory or polymorphic results |
| `fail(msg)` | Never passes | Marks a line that must not be reached |
All methods in one test
@IsTest
static void assertionVariants() {
Account acct = new Account(Name = 'Acme');
Object value = 'text';
Assert.isNull(acct.Id, 'Id is null before insert');
insert acct;
Assert.isNotNull(acct.Id, 'Id is set after insert');
Assert.isTrue(acct.Name.startsWith('Ac'), 'Name should start with Ac');
Assert.isFalse(acct.Name.contains('Z'), 'Name should not contain Z');
Assert.areNotEqual('Other', acct.Name, 'Name should not change');
Assert.isInstanceOfType(value, String.class, 'Value should be a String');
}Each message states what should be true. When isNotNull fails, the report reads "Id is set after insert", and you know the insert did not produce an Id.
Prefer the specific method
Compare two ways to check the same thing:
Assert.isTrue(result == 'JD', 'Initials wrong');reports only that the condition was false.Assert.areEqual('JD', result, 'Initials should be uppercase letters of each word');reports the expected and actual values.
Use isTrue and isFalse when the check is a real boolean, such as startsWith or contains. Use areEqual for anything you can compare to a known value.
The argument order is expected first, then actual. Reversing them still passes and fails correctly, but the failure output labels the values the wrong way round and misleads you.
Write messages that say what was expected
A good message describes the correct behavior, not the failure. Compare:
- Weak:
'Test failed' - Weak:
'Wrong count' - Strong:
'Exactly the 100 large accounts should be flagged'
The strong message names the rule being tested, so the reader knows which requirement broke.
Expected exceptions and `Assert.fail`
Assert.fail marks a path that must not be reached. It is the core of a negative test:
@IsTest
static void blankNameThrows() {
try {
StringUtil.initials(' ');
Assert.fail('Expected IllegalArgumentException for a blank name');
} catch (IllegalArgumentException e) {
Assert.areEqual('Name is required', e.getMessage(), 'Unexpected exception message');
}
}If initials throws, execution jumps to the catch block and fail never runs. If it does not throw, fail runs and the test fails. Assert.fail throws an AssertException, which the IllegalArgumentException catch block does not match, so the failure is not swallowed.
Common errors
- Catching too broadly. A
catch (Exception e)also catches theAssertExceptionfromAssert.fail, so the test passes when it should fail. Catch the specific exception type. - Asserting on stale data. After DML in the code under test, re-query the records. The in-memory variable may not match the database.
- Asserting a value that is always true.
Assert.isNotNull(new Account())proves nothing about your code. - Skipping the message. The message parameter is optional, but without it a failure gives little context.
Exercise
A test uses Assert.isTrue(acct.Rating == 'Hot', 'Rating check');. Rewrite it with a more specific method and a better message. Why is the new version easier to debug?
Show answer
Use Assert.areEqual('Hot', acct.Rating, 'Accounts with revenue of 1,000,000 or more should be rated Hot');. On failure, areEqual reports the expected value 'Hot' and the actual rating, while isTrue reports only that a condition was false. The new message also states the business rule being tested.
Exercise
A negative test wraps the call in try { ...; Assert.fail('Expected exception'); } catch (Exception e) { }. It passes even when the code does not throw. Why, and how do you fix it?
Show answer
Assert.fail throws an AssertException, which is a subclass of Exception, so the broad catch block swallows it and the test passes. Catch the specific exception type the code should throw, such as IllegalArgumentException, and assert on its message inside the catch block.