Sub topic 3
Verifying results with the Assert class
This chapter assumes you can write a basic Apex class, run a SOQL query, and use insert and update. It also assumes you know what a test class and an @IsTest method are. You will learn what the Assert class does, how its argument order works, and how to write failure messages that save debugging time. The next chapter compares the individual methods in more detail.
Why assertions decide whether a test is useful
A test method that calls your code and never checks the result can still raise code coverage. It proves only that the code ran without throwing an exception. An assertion is a statement of what must be true after the code runs. If the statement is false, the test fails.
The Assert class is the standard way to write assertions in Apex. Its methods are static, so you call them as Assert.areEqual(...). They replace the older System.assertEquals, System.assertNotEquals, and System.assert calls, which still work. In new code, prefer Assert. Its method names say what they check, and every method takes the same kind of optional message.
The shape of an assertion
Here is the class and test from the first example in this tutorial, with the assertion labeled.
public class StringUtil {
public static String initials(String fullName) {
if (String.isBlank(fullName)) {
throw new IllegalArgumentException('Name is required');
}
String result = '';
for (String part : fullName.trim().split(' ')) {
if (String.isNotBlank(part)) {
result += part.substring(0, 1).toUpperCase();
}
}
return result;
}
}
@IsTest
private class StringUtilTest {
@IsTest
static void initialsAreUppercased() {
String result = StringUtil.initials('jane doe');
Assert.areEqual('JD', result, 'Initials should be uppercase letters of each word');
}
}The test follows three steps, often called arrange, act, and assert:
- Arrange: build the input. Here the input is the string
'jane doe'. - Act: call the code under test and store the result in
result. - Assert: compare the result with what you expect.
Assert.areEqual takes three arguments, in this order:
| Position | Name | Meaning |
|---|---|---|
| 1 | expected | The value you know is correct, usually a literal |
| 2 | actual | The value your code produced |
| 3 | msg | Text that describes what the assertion checks |
The order matters because the failure output labels the values as "Expected" and "Actual". If you swap them, a failure tells you the opposite of the truth, and you can lose time chasing the wrong side. A habit that helps: put the literal first and the variable second.
What happens when an assertion fails
A failed assertion throws a System.AssertException. The test method stops at that line, and the platform records the test as failed. The failure output includes your message and, for comparison methods, the expected and actual values. Statements after the failed assertion do not run.
This has two consequences:
- A test method reports only its first failed assertion. If one method checks ten things, you may fix one failure only to find another.
- Because the method stops, any cleanup or later checks in the same method are skipped. Keep each method focused on one behavior.
flowchart TDThe diagram below shows the decision the platform makes at each assertion.
Writing messages that help
The message is the first thing you read when a test fails in a deployment log, often hours after you wrote it. Write it for a reader who has not seen the test.
Compare these two assertions on the same check:
Assert.areEqual(100, hot, 'Wrong');
Assert.areEqual(100, hot, 'Exactly the 100 large accounts should be flagged');The first message tells the reader nothing the failure output does not already say. The second says what the code should have done. A good message describes the expected behavior, not the failure. The platform already supplies "Expected" and "Actual" for comparison methods, so do not repeat them.
Some guidelines:
- State the rule: "Name should not change after update".
- Name the case when a method has several assertions: "Even-numbered accounts should be Hot".
- Avoid messages like "Test failed" or "Assertion error". The reader already knows.
- Keep it to one sentence. Put detail in the test method name.
If a method has several assertions of the same kind, distinct messages are what tell you which one failed.
Comparing values with areEqual and areNotEqual
Assert.areEqual(expected, actual, msg) passes when the two values are equal. Assert.areNotEqual(notExpected, actual, msg) passes when they differ. Both accept any data type, including primitives, collections, and SObjects.
Several details catch people out:
- String comparison in
Assert.areEqualis case-sensitive, unlike the==operator on strings in Apex, which ignores case.Assert.areEqual('jd', 'JD', 'msg')fails. This is useful when case is part of the contract, as it is ininitialsAreUppercased. - Number types matter. Compare an
Integercount with anIntegerliteral. ADecimalfield such asAnnualRevenueis best compared with a decimal or a value built from the same type, so that you know exactly what you compare. - Lists are compared element by element, in order. If your code does not guarantee an order, either add
ORDER BYto the query or compare sizes and membership separately. - A null expected value works with
areEqual, butAssert.isNullstates the intent better.
Checking truth, null, and type
The other methods check a single value:
@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');
}Reading through it:
Assert.isNullandAssert.isNotNullcheck whether a value isnull. The record has noIduntil theinsertruns, so the test checks both sides of that event.Assert.isTrueandAssert.isFalsecheck a Boolean expression. The failure output cannot show the values behind the expression, so the message has to carry the meaning.Assert.isInstanceOfType(instance, type, msg)passes when the instance is of the given type. It is useful forObjectvariables and for factories that return a parent type.
When both areEqual and isTrue could express a check, choose areEqual. Compare these two ways to check a count:
Assert.isTrue(accts.size() == 200, 'Should have 200 accounts');
Assert.areEqual(200, accts.size(), 'Should have 200 accounts');If the count is 199, the first reports only that a condition was false. The second reports "Expected: 200, Actual: 199", which points straight at the problem.
Asserting that code throws
Sometimes the correct behavior is an exception. Assert.fail(msg) fails the test unconditionally, and you place it right after the call that should throw.
@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');
}
}There are three outcomes:
- The code throws
IllegalArgumentException. The catch block runs and checks the message. The test passes. - The code throws nothing.
Assert.failruns and the test fails. Without that line, the test would pass silently even when the validation was removed. - The code throws a different exception. The catch block does not match it, so it escapes the method and the test fails.
Assert.fail throws an AssertException, which is not an IllegalArgumentException, so your own catch block does not swallow it. Be careful if you widen the catch to catch (Exception e). An AssertException is also an Exception, so a broad catch would catch the failure raised by Assert.fail and could let the test pass. Catch the most specific type you can.
Assertions that check the saved result
After DML, a variable in memory may not match what the database holds. Triggers, flows, and workflow rules can change a record after your code sets its fields. To check what was really saved, query the record again and assert on the queried copy:
@IsTest
static void rewardsNameIsSaved() {
Account acct = new Account(Name = 'Acme');
insert acct;
Account saved = [SELECT Name FROM Account WHERE Id = :acct.Id];
Assert.areEqual('Acme', saved.Name, 'Name should be saved as entered');
}Asserting on the in-memory object tells you what your test set. Asserting on the queried record tells you what the org stored.
Common mistakes
- Swapping expected and actual, so failure output misleads you.
- Asserting
Assert.isTrue(true, ...)or an always-true condition, which can never fail. - Putting many unrelated checks in one method, so only the first failure appears.
- Writing a test with no assertion at all. Coverage rises and nothing is verified.
- Leaving out the message and relying on a method name that is too general.
Exercises
Exercise
A test contains Assert.areEqual(result, 'JD', 'Initials should be uppercase'). The code returns 'J', so the test fails. What is wrong with how the assertion is written, and how does it affect the failure output?
Show answer
The arguments are in the wrong order. The expected value ('JD') should come first and the actual value (result) second. With the order swapped, the output labels 'J' as expected and 'JD' as actual, which points at the wrong side. The fixed call is Assert.areEqual('JD', result, 'Initials should be uppercase').
Exercise
Why does blankNameThrows call Assert.fail immediately after StringUtil.initials(' '), and what could go wrong if the catch block were catch (Exception e)?
Show answer
Assert.fail makes the test fail when no exception is thrown, which would otherwise pass silently. With catch (Exception e), the AssertException thrown by Assert.fail would itself be caught, and if the catch block's assertions happened to pass, the test would succeed even though the expected exception never occurred. Catching the specific IllegalArgumentException avoids this.
Exercise
You need to check that a list accts holds exactly 200 records. Which is better, Assert.isTrue(accts.size() == 200, msg) or Assert.areEqual(200, accts.size(), msg), and why?
Show answer
Assert.areEqual(200, accts.size(), msg) is better. On failure it reports both the expected and actual counts, while isTrue reports only that the condition was false.