Sub topic 5
Verifying Outcomes with the Assert Class
This chapter covers the Assert class, which is how an Apex test turns "this code ran" into "this code produced the right result". It assumes you can read basic Apex (classes, methods, collections, SOQL, DML) and that you know what an @isTest class is. Coverage and test quality get their own chapters, so this one stays on the assertions themselves.
Why assertions matter
Coverage records which lines executed. It does not record whether the results were correct. A test that calls a method and checks nothing can reach full coverage and still pass when the method is broken.
An assertion is a statement that compares an actual value with an expected one. If the comparison fails, the platform throws an exception that ends the test method and marks it as failed. That failure is the signal your test exists to produce.
The examples in this chapter use the DiscountCalculator class from earlier in the tutorial:
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);
}
}The Assert class
Assert is a built-in class in the System namespace, so you call its static methods without any import. It replaced the older System.assert, System.assertEquals and System.assertNotEquals methods. Those still work, but Assert has clearer method names and more of them. New code should use Assert.
| Method | Passes when |
|---|---|
| `Assert.areEqual(expected, actual, msg)` | The two values are equal |
| `Assert.areNotEqual(notExpected, actual, msg)` | The two values differ |
| `Assert.isTrue(condition, msg)` | The condition is `true` |
| `Assert.isFalse(condition, msg)` | The condition is `false` |
| `Assert.isNull(value, msg)` | The value is `null` |
| `Assert.isNotNull(value, msg)` | The value is not `null` |
| `Assert.fail(msg)` | Never. It always fails the test |
| `Assert.isInstanceOfType(instance, type, msg)` | The instance is of the given type |
| `Assert.isNotInstanceOfType(instance, type, msg)` | The instance is not of the given type |
The last argument of each method is an optional message. Always write one. When a test fails in a deployment log or a CI run, the message is often the only context you have.
Expected value first
Assert.areEqual takes the expected value as the first argument and the actual value as the second. Reversing them still compares correctly, but the failure output then reports the wrong value as "expected", which sends you looking in the wrong place. Keep the order consistent across the codebase.
@isTest
private class DiscountCalculatorTest {
@isTest
static void appliesPercentageDiscount() {
Decimal result = DiscountCalculator.apply(100, 10);
Assert.areEqual(90.00, result, 'A 10% discount on 100 should give 90');
}
}If apply returned 89, the failure would read roughly: expected 90.00, actual 89, with your message attached. You can see the problem without opening the debug log.
Choosing the right assertion
Use the most specific method that fits. Assert.areEqual(true, x) works, but Assert.isTrue(x) says what you mean. Specific methods also produce better failure output.
Prefer areEqual over isTrue(a == b). With isTrue, a failure only reports "condition was false". With areEqual, it reports both values.
@isTest
static void comparesBadlyAndWell() {
List<Account> accts = [SELECT Id FROM Account];
// Weak: a failure says only that the condition was false
Assert.isTrue(accts.size() == 0, 'Expected no accounts');
// Better: a failure shows the expected and actual counts
Assert.areEqual(0, accts.size(), 'Expected no accounts');
}What to assert on
A useful test asserts on the effect the code was supposed to have. The right target depends on what the code does.
- Return values. Compare the result with a known value, as in
appliesPercentageDiscount. - Database state. After DML, query the records again and assert on the queried values. The in-memory variable can differ from what was saved, especially when a trigger or flow changed the record.
- Counts. Use
[SELECT COUNT() ...]orlist.size()to check how many records were created, changed or left alone. - Side effects you did not intend. Assert that records which should not change are unchanged. This catches filters that are too broad.
The trigger test from the bulk example shows the database state and counts pattern. It re-queries the data instead of trusting the list held in memory:
trigger AccountTrigger on Account (before insert) {
for (Account a : Trigger.new) {
if (a.AnnualRevenue != null && a.AnnualRevenue > 1000000) {
a.Rating = 'Hot';
}
}
}
@isTest
private class AccountTriggerTest {
@isTest
static void marksHighRevenueAccountsHotInBulk() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
Decimal revenue = Math.mod(i, 2) == 0 ? 2000000 : 500;
accounts.add(new Account(Name = 'Acme ' + i, AnnualRevenue = revenue));
}
Test.startTest();
insert accounts;
Test.stopTest();
Integer hotCount = [SELECT COUNT() FROM Account WHERE Rating = 'Hot' AND Id IN :accounts];
Assert.areEqual(100, hotCount, 'Only the high-revenue half should be rated Hot');
}
}The assertion expects exactly 100. It would catch a trigger that rated every account Hot, and one that rated none. A weaker check such as Assert.isTrue(hotCount > 0) would pass in the first case, which is a bug.
Asserting that something throws
Apex has no assertThrows. The standard pattern is a try and catch block, with Assert.fail placed immediately after the call that should throw.
@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());
}
}Two details matter here.
First, Assert.fail throws its own exception, an AssertException. That exception is not an IllegalArgumentException, so the catch block does not swallow it and the test fails correctly. If you caught a generic Exception instead, the catch block would catch the failure raised by Assert.fail, and a test with no thrown exception would pass. Always catch the most specific exception type you expect.
Second, assert on the message or another property, not only on the type. Two different validation branches can throw the same type. Checking the message confirms that the right branch ran.
Failure messages that help
A good message describes the expectation in business terms, not the mechanics.
- Poor:
'Values not equal' - Better:
'A 10% discount on 100 should give 90'
For checks inside a loop, include the loop variable so you know which record failed:
@isTest
static void everyDiscountedAmountIsBelowOriginal() {
for (Integer percent = 1; percent <= 100; percent += 33) {
Decimal result = DiscountCalculator.apply(200, percent);
Assert.isTrue(result < 200, 'Discount of ' + percent + '% should reduce 200 but gave ' + result);
}
}Without the percent value in the message, a failure on the third iteration looks the same as a failure on the first.
The weak-test anti-pattern
This test executes the happy path and raises coverage, but it asserts nothing:
@isTest
private class WeakDiscountCalculatorTest {
@isTest
static void coversLinesButChecksNothing() {
DiscountCalculator.apply(100, 10);
}
}If someone changes the formula to amount + (amount * percent / 100), this test still passes. The method runs, nothing throws, and the coverage report stays green. The next chapter looks at this gap in detail. For now, treat a test method with no assertion as incomplete.
Common mistakes
- Asserting on the in-memory record after DML. Query the record again so you see what the database holds after triggers and automation ran.
- Comparing
Decimalvalues with different scales.Assert.areEqual(90.00, result)is safe forDecimalvalues, because equality compares the numeric value. Be careful if you compare formatted strings instead. - Using
isTruewhereareEqualfits. You lose the actual value from the failure output. - Leaving out the message. The failure still appears, but without context.
- Asserting on too little. A check that a list is not empty passes for one record or for 200. Assert the exact count when you know it.
- Relying on
System.debug. A debug statement never fails a test. Replace it with an assertion.
Exercise
A developer writes this test for DiscountCalculator.apply(100, -5). It passes even when apply never throws. Explain why, then rewrite the test so it fails in that case.
try {
DiscountCalculator.apply(100, -5);
Assert.fail('Expected an exception');
} catch (Exception e) {
Assert.isTrue(true);
}
Show answer
The catch block catches Exception, and AssertException from Assert.fail is a subtype of Exception. So when apply does not throw, Assert.fail throws, the catch block swallows it, and Assert.isTrue(true) passes. The fix is to catch the specific type and assert on the message:
try {
DiscountCalculator.apply(100, -5);
Assert.fail('Expected an IllegalArgumentException');
} catch (IllegalArgumentException e) {
Assert.isTrue(e.getMessage().contains('between 0 and 100'), 'Unexpected message: ' + e.getMessage());
}
Exercise
A trigger sets Rating = 'Hot' on accounts with revenue above 1,000,000. A test inserts 200 accounts, half above the threshold, then asserts Assert.isTrue(hotCount > 0). Name two bugs this assertion would miss and write a stronger one.
Show answer
It would miss a trigger that rates every account Hot (the count would be 200) and a trigger that stops after the first matching record (the count would be 1). The stronger assertion is Assert.areEqual(100, hotCount, 'Only the high-revenue half should be rated Hot');, preferably after a query that filters on the inserted account Ids.