Sub topic 6
Why high coverage can still mean weak tests
This chapter assumes you can read basic Apex (classes, methods, collections, SOQL, DML) and that you already know the 75% deployment rule and how coverage is counted. It uses the DiscountCalculator class from earlier in the tutorial. The goal is to show how a suite can report high coverage while checking almost nothing, and how to spot and fix that.
Coverage measures execution, not correctness
Salesforce counts a line as covered when a test runs it. The platform does not check whether the test confirmed that the line did the right thing. Coverage therefore answers "was this code run?" It does not answer "does this code work?"
Here is the class under test again:
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);
}
}And here is a test that covers the happy path without verifying anything:
@isTest
private class WeakDiscountCalculatorTest {
@isTest
static void coversLinesButChecksNothing() {
DiscountCalculator.apply(100, 10);
}
}This test executes the null check, the range check and the return statement. The two throw lines stay uncovered, but the rest is run. If you changed the formula to amount + (amount * percent / 100), the test would still pass. The calculation would be wrong, and the coverage number would not change.
What a weak test looks like
Weak tests tend to share a few traits. Learning to recognize them helps you in code review.
- No assertions. The test calls the method and ends. It can only fail if the code throws an unhandled exception.
- Assertions on the wrong thing. The test asserts that a result is not null, or that a list is not empty, when it could assert the exact value.
- Only the happy path. Every branch that handles bad input stays unexercised, or is exercised without checking the error.
- One record only. A trigger is tested with a single insert, so bulk bugs stay hidden.
- Swallowed exceptions. A
try/catchcatches an error and does nothing, so the test passes whether or not the code behaves.
The last trait deserves an example. This test looks like it checks the error path, but it passes even if no exception is thrown:
@isTest
private class SwallowedExceptionTest {
@isTest
static void looksLikeItChecksTheError() {
try {
DiscountCalculator.apply(100, 150);
} catch (IllegalArgumentException e) {
// Nothing is asserted here.
}
}
}If someone removed the range validation, apply would return a value, no exception would occur, and this test would still pass. The fix is the pattern used in the stronger test below: call Assert.fail right after the call that should throw, and assert on the caught exception.
The same code with a meaningful test
@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');
}
@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 things make these tests useful:
appliesPercentageDiscountcompares the result to an exact expected value. A wrong formula fails it.rejectsPercentOutOfRangefails in both bad cases. If no exception is thrown,Assert.failfails the test. If the wrong message appears, theAssert.isTruecheck fails.
A subtle point: Assert.fail throws an AssertException. Because the catch block only catches IllegalArgumentException, the AssertException is not swallowed. If you wrote catch (Exception e) instead, the catch would also catch the failure signal, and the test would pass for the wrong reason.
Why this happens in practice
Teams rarely write empty tests on purpose. Common pressures produce them:
- A deployment is blocked at 74% and someone adds quick tests to cross the line.
- A large class is inherited with no tests, and the first goal is just to reach the threshold.
- Tests are generated or copied from a template that only calls methods.
- Assertions are hard to write because the code has side effects, such as updating records, so the author skips them.
The last point is a design signal. If you cannot easily say what a method should produce, the method may do too much. Splitting it into smaller methods with clear inputs and outputs makes both testing and assertions simpler.
Branches and conditions hide in single lines
Line coverage is coarse. A single line can contain several decisions, and one execution of that line counts it as covered.
if (amount == null || percent == null) {This line holds two conditions. A test that passes null for amount runs the line, but the percent == null check is never evaluated because || stops at the first true condition. The line shows as covered, but one half of the logic was never tested.
The same applies to ternary expressions:
Decimal revenue = Math.mod(i, 2) == 0 ? 2000000 : 500;One execution covers the line even if only one side of the ? was taken. To test both sides, you need inputs that make the condition true and false. A table of cases helps you plan this.
| Condition in `DiscountCalculator` | Input that exercises it | Expected outcome |
|---|---|---|
| `amount == null` | `apply(null, 10)` | `IllegalArgumentException` |
| `percent == null` | `apply(100, null)` | `IllegalArgumentException` |
| `percent < 0` | `apply(100, -1)` | `IllegalArgumentException` |
| `percent > 100` | `apply(100, 101)` | `IllegalArgumentException` |
| Boundary `percent == 0` | `apply(100, 0)` | `100` |
| Boundary `percent == 100` | `apply(100, 100)` | `0` |
| Typical value | `apply(100, 10)` | `90` |
The boundary rows matter most. A change from percent > 100 to percent >= 100 would be caught by the percent == 100 case and missed by every other row.
Reading a coverage report critically
A coverage percentage is a hint about where tests are missing, not a measure of quality. Use it in one direction only:
- Low coverage tells you something. Uncovered lines are definitely untested.
- High coverage tells you little. Covered lines may be tested well or not at all.
When you look at a class in the Developer Console or in an IDE, check the uncovered lines first. Then pick a few covered lines and ask: "If I broke this line on purpose, would a test fail?" If the answer is no, you have found a weak spot.
You can try this by hand. This is a lightweight form of mutation testing:
- Make a small deliberate change to the code, such as flipping
-to+or>to>=. - Run the tests for that class.
- If every test still passes, the tests do not protect that behavior. Add an assertion or a new case.
- Revert the change.
Do this only in a scratch org or sandbox, and revert immediately.
A checklist for each test method
Before you consider a test finished, check these points:
- Does it contain at least one assertion about a specific, expected value or state?
- Would it fail if the main logic returned a wrong but plausible result?
- Does it use a message in each assertion that explains what went wrong?
- For expected errors, does it fail when no error occurs, and does it check the error type or message?
- Does it cover both outcomes of each important condition, including boundaries?
- For triggers and batch-style code, does it use more than one record?
Common mistakes and how to fix them
| Mistake | Why it is a problem | Fix |
|---|---|---|
| Test has no assertion | Cannot fail on wrong results | Add `Assert.areEqual` on the output or on queried records |
| Asserting only `!= null` | A wrong value still passes | Assert the exact expected value |
| `catch (Exception e)` around `Assert.fail` | Swallows the failure signal | Catch the specific exception type |
| Empty `catch` block | Passes with or without an error | Assert on the exception, and call `Assert.fail` after the call |
| Asserting on in-memory records after DML | Values set by triggers or workflows are not reflected | Re-query the records, then assert |
| Chasing 100% on every class | Effort goes to trivial lines | Prioritize logic with business impact |
The re-query row catches many people. After insert accounts, fields set by an after trigger or other automation may not be visible on the in-memory objects. Query the records and assert on what the database holds.
Exercise
A teammate's test calls DiscountCalculator.apply(100, 150) inside a try block and has catch (Exception e) { Assert.isTrue(true); }. The class shows full coverage for the validation branch. Explain why this test is weak, and rewrite the test so it fails when validation is removed.
Show answer
The test passes whether or not an exception is thrown. If the range check is deleted, apply returns a value, the catch block never runs, and the test still passes. The Assert.isTrue(true) line also checks nothing. Rewrite it with a specific exception type and Assert.fail:
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());
}
Now removing the validation makes Assert.fail run, and the test fails.
Exercise
You change amount - (amount * percent / 100) to amount - (amount * percent / 10) in DiscountCalculator. Which of the two tests, WeakDiscountCalculatorTest.coversLinesButChecksNothing or DiscountCalculatorTest.appliesPercentageDiscount, fails, and why?
Show answer
Only appliesPercentageDiscount fails. With the changed formula, apply(100, 10) returns 0 instead of 90, so Assert.areEqual(90.00, result, ...) fails. The weak test calls the method and never inspects the result, so it still passes and the coverage number stays the same.