Sub topic 4
Choosing the right assertion method
This chapter assumes you can write an @IsTest method, run it, and read a basic failure in the Apex Test Execution view. It also assumes you know SOQL and DML. Here you will learn which Assert method fits each kind of check, and how that choice changes the failure message you get when a test breaks.
Start from the question you are asking
Every assertion answers one question about the code under test. The Assert class has a method for each common question. A method that matches your question tells you what went wrong when the test fails.
| Question | Method | Fails when |
|---|---|---|
| Is the value exactly what I expect? | `Assert.areEqual(expected, actual, msg)` | The two values differ |
| Did the value change from a known bad or old value? | `Assert.areNotEqual(notExpected, actual, msg)` | The two values are equal |
| Is this condition true? | `Assert.isTrue(condition, msg)` | The condition is false |
| Is this condition false? | `Assert.isFalse(condition, msg)` | The condition is true |
| Is there no value? | `Assert.isNull(value, msg)` | The value is not null |
| Is there a value? | `Assert.isNotNull(value, msg)` | The value is null |
| Is this object of the right type? | `Assert.isInstanceOfType(instance, type, msg)` | The object is not of that type |
| Should this line never be reached? | `Assert.fail(msg)` | Always, when executed |
The message is the last argument of every method. It is optional in the language, but you should always supply it.
areEqual: the default choice
Use Assert.areEqual whenever you know the exact result. The expected value comes first and the actual value second. If you swap them, the test still passes or fails correctly, but the failure message reports the two values under the wrong labels. That sends you looking in the wrong place.
Assert.areEqual('JD', result, 'Initials should be uppercase letters of each word');When this fails, the output shows both values, so you can see the difference without a debugger. That is the main advantage over isTrue. Compare two ways of checking the same thing:
Assert.isTrue(result == 'JD', 'Wrong initials');
Assert.areEqual('JD', result, 'Wrong initials');If result is 'J', the first form reports only your message. The second reports your message plus the expected and actual values. Prefer the second.
areEqual also works on numbers, dates, Ids, lists, sets, and maps. For collections, check the size first with its own assertion. A failed size check names the real problem, which is a different number of records. A failed collection comparison does not.
List<Account> flagged = [SELECT Id FROM Account WHERE Rating = 'Hot'];
Assert.areEqual(100, flagged.size(), 'Number of flagged accounts');
Assert.areEqual('Hot', flagged[0].Rating, 'First flagged account rating');Read the first element only after the size check passes. Otherwise an empty list raises a ListException and hides the real failure.
areNotEqual: use it for "changed", not for "correct"
Assert.areNotEqual proves that a value is not something specific. It is a weak check, because many wrong values also differ from the one you named. Use it when the exact new value is out of your control, such as a generated Id or a timestamp, and the point of the test is that the value changed.
String before = acct.Description;
AccountService.refreshDescription(acct);
Assert.areNotEqual(before, acct.Description, 'Description should be regenerated');If you do know the new value, use areEqual for it. A test that only says "not the old value" passes when the code writes garbage.
isTrue and isFalse: for conditions with no single expected value
isTrue and isFalse suit checks that are naturally boolean, such as startsWith, contains, isEmpty, or Limits comparisons. They report only that the condition was false, so the message has to carry the detail.
Assert.isTrue(acct.Name.startsWith('Ac'), 'Name should start with Ac but was ' + acct.Name);
Assert.isFalse(acct.Name.contains('Z'), 'Name should not contain Z');Put the actual value in the message when you use isTrue on a comparison. This gives you back the information that areEqual would have given for free.
Do not pass a boolean to areEqual. Assert.areEqual(true, flag, msg) works, but Assert.isTrue(flag, msg) says the same thing more directly.
isNull and isNotNull: presence checks
Use these when the question is whether a value exists. Typical cases are an Id before and after insert, a lookup field that should be filled in, or a method that returns null when nothing matches.
Account acct = new Account(Name = 'Acme');
Assert.isNull(acct.Id, 'Id is null before insert');
insert acct;
Assert.isNotNull(acct.Id, 'Id is set after insert');An isNotNull check alone rarely proves behavior. It tells you something was returned, not that it was correct. Follow it with an areEqual on the content you care about.
isInstanceOfType: checking what you got back
Assert.isInstanceOfType(instance, type, msg) passes when the object is an instance of the given type. It is useful when code returns a general type, such as Object, SObject, or an interface, and the concrete type matters. Typical examples are a factory method that returns different handler classes, or a method that returns an SObject that should be an Account.
Object value = 'text';
Assert.isInstanceOfType(value, String.class, 'Value should be a String');Pass the type as String.class, Account.class, or MyHandler.class. Null is not an instance of any type, so a null value fails this assertion.
fail: marking a path that must not run
Assert.fail(msg) fails the test whenever it executes. Its main use is the negative test: you call code that should throw, and place fail on the line after the call. If no exception is thrown, fail runs and the test fails.
@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');
}
}Catch the specific exception type, not Exception. The fail call throws its own AssertException. A catch block for the specific type lets that failure pass through, so a missing exception still fails the test.
The test is also incomplete without the assertion inside the catch block. Without it, the test passes for any IllegalArgumentException, including one raised for the wrong reason.
All the methods in one runnable test
This class puts the earlier checks together. It needs no helper class, so you can paste it into an org and run it.
@IsTest
private class AssertionChoiceTest {
@IsTest
static void chooseByQuestion() {
Account acct = new Account(Name = 'Acme', AnnualRevenue = 5000);
Assert.isNull(acct.Id, 'Id is null before insert');
insert acct;
Assert.isNotNull(acct.Id, 'Id is set after insert');
Account saved = [SELECT Id, Name, AnnualRevenue FROM Account WHERE Id = :acct.Id];
Assert.areEqual('Acme', saved.Name, 'Name should be saved as entered');
Assert.areEqual(5000, saved.AnnualRevenue, 'Revenue should be saved as entered');
Assert.areNotEqual('Other', saved.Name, 'Name should not change');
Assert.isTrue(saved.Name.startsWith('Ac'), 'Name should start with Ac but was ' + saved.Name);
Assert.isFalse(saved.Name.contains('Z'), 'Name should not contain Z');
Object record = saved;
Assert.isInstanceOfType(record, Account.class, 'Record should be an Account');
}
}Writing failure messages that help
The message is the first thing you read when a test fails in a deployment pipeline. Write it for someone who has not seen the test.
- State the expectation, not the failure. Write
'Exactly the 100 large accounts should be flagged', not'Wrong count'. - Name the object or scenario if the test has several assertions of the same kind.
- With
isTrueandisFalse, add the actual value to the message by concatenation. - Do not repeat the expected value in a message beside
areEqual. The failure output already shows it.
Common mistakes
- Asserting on the in-memory object after DML. If code updates records in a trigger or service, re-query before asserting, as the bulk test in the spine does. The variable you hold may not reflect database changes.
- Using
isNotNullas the only check. It proves the code returned something, not the right thing. - Putting several unrelated checks in one
isTrue. Usea && band you cannot tell which half failed. Make two assertions. - Omitting
Assert.failin a negative test. The test then passes when no exception is thrown, which is the case it should catch. - Asserting too loosely. If you know the value, use
areEqual. Each step down the table loses information.
Exercise
A method Integer applyDiscount(Integer price) should return 90 for a price of 100. A test calls it and runs Assert.isTrue(result > 0, 'Discount applied');. Which assertion should replace it, and why does the original fail to catch a bug that returns 100?
Show answer
Use Assert.areEqual(90, result, 'Discounted price for 100');. The original check passes for any positive number, including 100 (no discount) or 1. Because the expected value is known, areEqual verifies it exactly, and on failure it shows both the expected and actual values.
Exercise
You test a method that must throw IllegalArgumentException for a null input. Your test calls the method inside try and has a catch (IllegalArgumentException e) block, but no Assert.fail line. What bug does this test miss, and how do you fix it?
Show answer
It passes when the method throws nothing, because the catch block is never entered and no assertion runs. Add Assert.fail('Expected IllegalArgumentException for null input'); on the line right after the method call, and add an Assert.areEqual on e.getMessage() in the catch block.