Sub topic 13
Habits of reliable tests
This chapter pulls the earlier chapters together into working habits. It assumes you can write a test class with @IsTest methods, use the Assert class, create data with @TestSetup, and use Test.startTest and Test.stopTest. It also assumes you know basic SOQL, DML, and governor limits. Nothing here is new syntax. The chapter is about which tests to write and how to keep them trustworthy over years of org changes.
A reliable test has three properties:
- It fails when the behavior it protects breaks.
- It passes whenever that behavior works, whatever the org's data, the time of day, or the order of other tests.
- When it fails, the message tells you what went wrong.
Assert behavior, not coverage
Salesforce requires 75% Apex coverage across the org to deploy to production, and each trigger needs some coverage. The platform measures only which lines ran. It does not check whether anything was verified. A test with no assertions can reach 100% coverage and still protect nothing.
Here is the service from the bulk-testing chapter, followed by a test that only covers it:
public class AccountService {
public static void flagLargeAccounts(List<Account> accounts) {
for (Account a : accounts) {
if (a.AnnualRevenue != null && a.AnnualRevenue >= 1000000) {
a.Rating = 'Hot';
}
}
update accounts;
}
}
@IsTest
private class AccountServiceCoverageOnlyTest {
@IsTest
static void coverageOnly() {
Account a = new Account(Name = 'Big', AnnualRevenue = 2000000);
insert a;
AccountService.flagLargeAccounts(new List<Account>{ a });
}
}Change >= to >, or delete the Rating assignment, and this test still passes. The next version asserts the outcome and probes the boundary on both sides:
@IsTest
private class AccountServiceBoundaryTest {
@IsTest
static void flagsAtThresholdButNotBelow() {
Account atLimit = new Account(Name = 'At limit', AnnualRevenue = 1000000);
Account below = new Account(Name = 'Below limit', AnnualRevenue = 999999);
insert new List<Account>{ atLimit, below };
Test.startTest();
AccountService.flagLargeAccounts(new List<Account>{ atLimit, below });
Test.stopTest();
Map<Id, Account> saved = new Map<Id, Account>(
[SELECT Id, Rating FROM Account WHERE Id IN :new Set<Id>{ atLimit.Id, below.Id }]
);
Assert.areEqual('Hot', saved.get(atLimit.Id).Rating, 'Revenue of exactly 1,000,000 should be flagged');
Assert.isNull(saved.get(below.Id).Rating, 'Revenue of 999,999 should not be flagged');
}
}This test also re-queries the records. Asserting on the in-memory object only shows that the code changed the variable. Re-querying shows that the change was saved.
A quick way to check any test is to break the code on purpose. Flip a comparison, remove a line, or return early, then run the test. If it still passes, it is not protecting that line. Revert the change afterward.
One behavior per test method
A test method should answer one question. If it fails, its name should tell you what broke without reading the body. Name methods after the behavior and the condition, as in flagsAtThresholdButNotBelow or blankNameThrows. Avoid names such as test1 or testAccountService.
Several assertions in one method are fine when they describe one outcome, for example checking each field of a single saved record. Separate methods are better for separate scenarios. When one method covers five scenarios, the first failed assertion stops the method and hides the other four results.
Write each failure message as a sentence about what should have been true:
- Weak:
'Wrong value' - Better:
'Revenue of exactly 1,000,000 should be flagged'
The report shows the expected value, the actual value, and your message. You only need to supply the reasoning.
Own your data
Tests should create the records they need and nothing else.
- Leave
SeeAllDataoff. Test methods cannot see the org's existing data by default. Adding@IsTest(SeeAllData=true)makes the result depend on whatever is in that sandbox or production org. Use it only for the few cases that need it, such as some Connect API features. - Never hardcode record IDs. IDs differ between orgs. Query by a stable field such as a profile name, or use the ID of a record you just inserted.
- Use
@TestSetupfor shared records. It runs once per class. Each test method gets a fresh copy of that data, and its own changes are rolled back afterward. - Share creation logic in a factory. Define required fields in one place so a new validation rule means one edit instead of fifty.
A minimal factory looks like this:
@IsTest
public class TestDataFactory {
public static List<Account> createAccounts(Integer count, Decimal revenue, Boolean doInsert) {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < count; i++) {
accounts.add(new Account(Name = 'Factory Account ' + i, AnnualRevenue = revenue));
}
if (doInsert) {
insert accounts;
}
return accounts;
}
}The doInsert flag lets a test change fields before inserting, or run a negative case that should fail on insert.
Query results need the same care. A query without ORDER BY has no guaranteed order, so results[0] can change between runs. Look records up by ID, as the boundary test above does with a Map, or add an explicit ORDER BY.
Do not depend on time, order, or luck
Three sources of flaky tests are common.
- The current date. A test that hardcodes
Date.newInstance(2026, 12, 1)passes until that date arrives. Build dates relative to now, for exampleDate.today().addDays(-1)for an overdue record. - Test method order. The platform does not promise an order, so no method may rely on another having run. Put shared prerequisites in
@TestSetup. - Unique values. Fields like
User.Usernamemust be unique across all of Salesforce. AddSystem.currentTimeMillis()or a counter, as theSystem.runAsexample did. Hardcoded unique values fail the second time they are used, for example when two deployments run at once.
Randomness is the fourth source. If the code under test uses a random value, isolate it behind a method you can control, or assert on properties that hold for every value.
Cover all three paths
Most classes need at least these three kinds of test:
| Path | What it proves | Typical tool |
|---|---|---|
| Positive | The normal case produces the right result | `Assert.areEqual` on re-queried data |
| Negative | Bad input fails in the expected way | `try`/`catch` with `Assert.fail` |
| Bulk | Logic holds for 200 records without hitting limits | `@TestSetup` or a factory with 200 records |
Add user-context tests with System.runAs when sharing or permissions matter, and add async or callout tests when the code uses them.
Be careful with the negative path:
@IsTest
static void blankNameThrowsSpecificException() {
try {
StringUtil.initials(' ');
Assert.fail('Expected IllegalArgumentException for a blank name');
} catch (IllegalArgumentException e) {
Assert.areEqual('Name is required', e.getMessage(), 'Unexpected exception message');
}
}Assert.fail throws an AssertException. If you catch the base Exception type instead of the specific one, the catch block swallows the failure and the test passes when it should not. Catch the narrowest type the code is supposed to throw.
Keep `startTest` and `stopTest` narrow
Call Test.startTest() once per method, immediately before the code under test, and Test.stopTest() immediately after. Everything before startTest (data creation, queries for setup) uses the setup limits. Everything between the two calls gets a fresh set of governor limits, so a bulk test shows whether the code alone stays within limits. stopTest also forces queued asynchronous work, such as Queueable, Batch, and future jobs, to finish. Put your assertions after stopTest so they see the finished results.
If you wrap the entire method in startTest and stopTest, setup work counts against the code's limits. A test that should pass can then fail, and a test that should fail can hide a limits problem.
Review checklist
You can apply the habits as a short review of any test:
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Test passes after you break the code | No assertions, or assertions only on in-memory objects | Re-query and assert on saved values |
| Test passes in a sandbox, fails in production | `SeeAllData=true` or a hardcoded ID | Create the data in the test |
| Test fails only after a certain date | Hardcoded date | Use `Date.today().addDays(n)` |
| `results[0]` is a different record each run | Query has no `ORDER BY` | Order the query or look up by ID |
| Negative test never fails | Catching `Exception` around `Assert.fail` | Catch the specific type |
| Limits error only in the test | Setup work done between `startTest` and `stopTest` | Move setup before `startTest` |
| Duplicate username on insert | Fixed `UserName` value | Append `System.currentTimeMillis()` |
Habits to keep
- Treat coverage as a smoke alarm. A low number shows untested code, but a high number does not show that the tests are good.
- Break the code on purpose now and then to confirm a test can fail.
- Test boundaries at the exact threshold and one step on each side.
- Write failure messages for the person reading a failed deployment log at an inconvenient hour.
- Keep each test independent, so it runs alone or in any order and gives the same result.
Exercise
A teammate's test inserts 200 accounts with a factory, calls AccountService.flagLargeAccounts on them, and has no assertions. Coverage for the class is 100%. List four changes that make the test reliable.
Show answer
(1) Re-query the accounts after the call and assert on the saved Rating values, for example with Assert.areEqual(100, hot, 'Exactly the 100 large accounts should be flagged'). (2) Wrap only the service call in Test.startTest() and Test.stopTest(), so the 200-record run gets fresh limits and the setup does not count against it. (3) Add boundary records with revenue of exactly 1,000,000 and 999,999 to check the comparison. (4) Add a test for accounts with null AnnualRevenue and ensure the data is created by the test, not read from the org with SeeAllData. To confirm the new assertions work, temporarily change >= to > and check that the boundary test fails.