Sub topic 13
Habits of reliable tests
This chapter assumes you can write an @IsTest method, use @TestSetup, and call Assert methods. It pulls the earlier chapters into a checklist you can apply to any test class.
Test behavior, not lines
Salesforce requires 75% code coverage to deploy to production. Coverage only shows that a line ran. It does not show that the line produced the right result. A test with no assertions can reach 100% coverage and still pass when the code is broken.
Compare these two tests for the AccountService class from the bulk testing chapter:
@IsTest
private class AccountServiceHabitsTest {
@IsTest
static void coversButProvesNothing() {
Account a = new Account(Name = 'Big', AnnualRevenue = 2000000);
insert a;
AccountService.flagLargeAccounts(new List<Account>{ a });
}
@IsTest
static void flagsLargeAndSkipsSmall() {
Account big = new Account(Name = 'Big', AnnualRevenue = 2000000);
Account small = new Account(Name = 'Small', AnnualRevenue = 500);
insert new List<Account>{ big, small };
Test.startTest();
AccountService.flagLargeAccounts(new List<Account>{ big, small });
Test.stopTest();
Account savedBig = [SELECT Rating FROM Account WHERE Id = :big.Id];
Account savedSmall = [SELECT Rating FROM Account WHERE Id = :small.Id];
Assert.areEqual('Hot', savedBig.Rating, 'Large account should be Hot');
Assert.isNull(savedSmall.Rating, 'Small account should keep a blank rating');
}
}The first method covers every line of flagLargeAccounts. If someone deletes the Rating = 'Hot' line, it still passes. The second method fails in that case, because it checks the saved result for both the large and the small account.
The Arrange, Act, Assert shape
Give each test method three parts, in this order:
- Arrange: create the data and set the context.
- Act: call the code under test, usually between
Test.startTest()andTest.stopTest(). - Assert: re-query the database and check the outcome.
A checklist of habits
| Habit | Why it matters |
|---|---|
| One behavior per method | A failure points to one cause. |
| Descriptive method names | `blankNameThrows` explains a failure better than `test1`. |
| A message on every assertion | The failure log says what was expected. |
| Create your own data | Tests do not break when org data changes. |
| Test with 200 records | Exposes SOQL or DML inside loops. |
| Test the error path | `Assert.fail` proves an exception really happens. |
| Re-query before asserting | Checks what was saved, not the in-memory object. |
| Mock callouts | Tests never depend on an external service. |
Habits that prevent flaky tests
A flaky test passes on some runs and fails on others. Common causes are:
- Relying on
@SeeAllData=true. Tests then depend on whatever data the org holds. Create the records you need in@TestSetupor a factory instead. - Hard-coded IDs, names, or usernames. Build unique values, as the
System.runAsexample did withSystem.currentTimeMillis(). - Assuming query order. Add
ORDER BYor look records up by ID. - Sharing state between methods. Each method's data changes roll back, so do not write tests that need another test to run first.
- Asserting on dates or times computed from
System.now()without allowing for the clock moving between lines.
Keep tests maintainable
Move repeated record creation into a test data factory so a new required field changes one class, not forty. Keep test classes private and name them after the class under test, such as AccountServiceTest. Assert on business outcomes such as field values, record counts, and thrown messages. Avoid asserting on internal details that change during refactoring.
Before you finish a test class, read each method and ask, "If I broke the production code, which assertion would fail?" If you cannot name one, the test only adds coverage.
Exercise
A test inserts an Account, calls a method that should set its Rating to 'Hot', and has no assertions. Coverage is 100%. What is wrong, and how do you fix it?
Show answer
Coverage shows the lines ran, not that they worked, so the test passes even if the method does nothing. Fix it by re-querying the Account after Test.stopTest() and adding Assert.areEqual('Hot', saved.Rating, 'Account should be rated Hot'). Also add a case that should not be flagged.
Exercise
Why is catching a generic Exception around Assert.fail a problem in a negative test?
Show answer
Assert.fail throws an AssertException, which is also an Exception. A generic catch block swallows it, so the test passes even when the expected exception was never thrown. Catch only the specific exception type you expect.