Sub topic 15
Building a test strategy that stays useful over time
Earlier chapters covered how coverage is counted, how to write assertions, and how to test bulk and failure behavior. This chapter ties those pieces into a strategy you can keep up as the codebase grows. It assumes you can write an Apex test class with @isTest, use Test.startTest and Test.stopTest, and read a coverage report.
What a strategy has to achieve
A test suite has three jobs, and they pull in different directions:
- Pass the deployment gate. Production deployments need at least 75% Apex coverage across the org. Every trigger needs some coverage, and every test that runs must pass.
- Catch real regressions. A test that cannot fail when behavior breaks has no value.
- Stay cheap to maintain. If tests are slow, flaky or tangled together, developers stop trusting them and start ignoring failures.
Coverage only measures the first job. A strategy is the set of habits that also covers the other two.
Treat 75% as a floor
The 75% number is the platform's minimum, not a quality target. Teams that aim for exactly 75% tend to drift below it as soon as a large untested class is added. Teams that chase 100% tend to write assertion-free tests to close the last gaps.
A workable policy has three parts:
- Set a higher bar for new code, such as 85% to 90% per class, enforced in code review.
- Require every test method to contain at least one assertion that would fail if the behavior broke.
- Do not write tests for trivial getters or empty wrappers just to move a percentage.
Decide what to test by risk
Not all code deserves the same effort. Spend more on code that is complex, widely used, or expensive to get wrong.
| Code type | Highest-value tests |
|---|---|
| Calculation and validation logic | Boundary values, invalid input, exact result assertions |
| Triggers and trigger handlers | 200-record bulk insert and update, mixed matching and non-matching records |
| Callout classes | Success response, error status code, malformed body, all with `Test.setMock` |
| Asynchronous jobs | Work is done after `Test.stopTest()`, failures do not corrupt data |
| Code gated by sharing or permissions | `System.runAs` with a user who has access and one who does not |
A repeatable checklist for each unit
The same questions apply to almost every class. The diagram shows the order to ask them in.
Applying this to the DiscountCalculator class from earlier chapters gives a small table-driven test. It checks both edges of the valid range and several invalid values, which catches off-by-one mistakes in the range check.
@isTest
private class DiscountCalculatorBoundaryTest {
@isTest
static void acceptsBothEdgesOfTheValidRange() {
Assert.areEqual(100.00, DiscountCalculator.apply(100, 0), '0% should leave the amount unchanged');
Assert.areEqual(0.00, DiscountCalculator.apply(100, 100), '100% should reduce the amount to zero');
}
@isTest
static void rejectsEachInvalidPercent() {
List<Decimal> invalidPercents = new List<Decimal>{ -1, -0.01, 100.01, 150 };
for (Decimal percent : invalidPercents) {
Boolean thrown = false;
try {
DiscountCalculator.apply(100, percent);
} catch (IllegalArgumentException e) {
thrown = true;
}
Assert.isTrue(thrown, 'Expected an exception for percent ' + percent);
}
}
@isTest
static void rejectsMissingArguments() {
Boolean thrown = false;
try {
DiscountCalculator.apply(null, 10);
} catch (IllegalArgumentException e) {
thrown = true;
}
Assert.isTrue(thrown, 'A null amount should be rejected');
}
}The failure message in each assertion names the input that failed. When a test fails in a pipeline months later, that message is often all the reader has.
Share data builders, not data
Tests that each build their own records in slightly different ways are expensive to change. When a new required field or validation rule is added, dozens of classes break at once. A single factory class turns that into one fix.
@isTest
public class TestDataFactory {
public static List<Account> buildAccounts(Integer count, Decimal revenue) {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < count; i++) {
accounts.add(new Account(Name = 'Test Account ' + i, AnnualRevenue = revenue));
}
return accounts;
}
public static List<Account> createAccounts(Integer count, Decimal revenue) {
List<Account> accounts = buildAccounts(count, revenue);
insert accounts;
return accounts;
}
}The factory has two methods on purpose. buildAccounts returns unsaved records, so a test can change a field before inserting. createAccounts saves them for tests that only need existing data. Marking the class @isTest keeps it out of your org's Apex code size limit and makes it usable only from tests.
Some rules keep data from becoming a source of fragile tests:
- Create the data the test needs. Do not use
@isTest(SeeAllData=true)unless the code truly depends on org data that cannot be created, because it ties results to whatever exists in the org. - Use
@TestSetupfor data that many methods in one class share. Each test method gets a fresh copy, so changes made in one method do not leak into another. - Never hard-code record IDs, usernames or dates that will go stale.
- Do not rely on the order tests run in.
Keep tests focused on behavior
A test that checks how the code works internally breaks every time the code is refactored. A test that checks what the code does survives refactoring. Compare these two assertions for the same trigger:
- Brittle: asserting that a particular private helper method was called.
- Durable: asserting that the account's
Ratingfield is'Hot'after insert.
For the same reason, assert on the parts of an error message that matter, such as contains('between 0 and 100'), rather than the full sentence. Then rewording a message does not fail unrelated tests.
The sabotage check
Coverage cannot tell you whether a test is any good. A quick manual check can. Before merging important logic, temporarily break the code and confirm a test fails.
- Change
amount - (amount * percent / 100)toamount + (amount * percent / 100)in a scratch copy. - Run the class's tests.
- If everything still passes, the tests execute the line but do not verify it. Add the missing assertion.
- Revert the change.
This takes two minutes and is the most reliable way to find a test like WeakDiscountCalculatorTest, which calls the method and checks nothing.
Automate the run
A strategy that depends on people remembering to run tests will decay. Run the local test suite automatically on every pull request, against a scratch org or sandbox.
sf apex run test \
--test-level RunLocalTests \
--code-coverage \
--result-format human \
--wait 10RunLocalTests runs every test in your org except tests that come from managed packages, which is what a production deployment runs by default. Fail the pipeline when any test fails. Fail it, or at least warn, when coverage on changed classes drops below your team's bar.
Signs that a suite is decaying
| Symptom | Likely cause | Response |
|---|---|---|
| A test passes on rerun after failing | Dependence on order, time or shared org data | Make the test create its own data and fix dates |
| Many tests break from one field change | Data built inline in every class | Move construction into the factory |
| Test runs take far longer each month | Tests insert more data than they need, or too many use `SeeAllData` | Reduce volume except in bulk tests, and remove `SeeAllData` |
| Coverage is high but production bugs keep appearing | Assertion-free or happy-path-only tests | Run sabotage checks, add negative and bulk tests |
| Tests for deleted features still exist | No cleanup step | Delete tests with the code they cover |
Putting it together
A sustainable strategy is a small set of rules applied consistently:
- Use 75% as the gate and a higher, reviewed bar for new code.
- Assert outcomes in every test.
- Cover the happy path, bulk, failure and permission cases for risky code.
- Build data through one factory and avoid
SeeAllData. - Mock callouts, and run asynchronous code between
Test.startTest()andTest.stopTest(). - Run the suite automatically and treat red as blocking.
- Spot-check important tests with a sabotage check.
Exercise
A class has 92% coverage and its tests all pass, but a bug in its discount formula reaches production. Name two checks from this chapter that would help find whether the tests are weak, and say what each would reveal.
Show answer
The sabotage check and a review of assertions. Temporarily changing the formula and re-running the tests shows whether any test fails. If none does, the tests execute the line without verifying the result. Reviewing the test methods for assertions shows whether each one compares an actual result to an expected value, as appliesPercentageDiscount does, or only calls the method, as WeakDiscountCalculatorTest does. Boundary and negative tests would also help, since formulas often fail at edge values.
Exercise
Twenty test classes each build Account records inline. A new required field is added to Account and all twenty classes fail. What change prevents this from recurring, and why does buildAccounts return unsaved records?
Show answer
Move record construction into a shared @isTest factory class so the new required field is set in one place. buildAccounts returns unsaved records so a test can adjust fields, such as setting a specific revenue, before it calls insert. Tests that only need saved data can call createAccounts instead.