November 26, 20269 minutes
Part 3 of 5
A fully covered, green test suite can still miss a one-symbol bug. PIT plants bugs on purpose and counts how many your tests notice. Learn to read the report and fix the survivors.
Last time we ended with a suite that looks perfect. Every line runs, every branch runs, and the build is green. Now a tool quietly changes one comparison in the shipping code: at least a hundred becomes more than a hundred. Then it runs your tests. They all pass. The bug survived, and no test noticed. That is what coverage can’t see, and what PIT is built to find.
Prefer to watch? The narrated video covers the same lesson (about ten minutes). The article follows it section by section, with diagrams, the Maven equivalent and a little extra depth.
This is the second of two lessons on measuring your tests, and it starts exactly where the first one ended. Here is the same method from before: free shipping at a hundred or more, the flat rate otherwise, and fifteen extra for express.
public double cost(Order order) {
double shipping;
if (order.total() >= 100) {
shipping = 0;
} else {
shipping = 7.99;
}
if (order.express()) {
shipping += 15;
}
return shipping;
}And here is the suite we finished with. Three tests, all passing, and only weak checks: no assertion, above zero, and below ten.
class ShippingCalculatorTest {
private final ShippingCalculator calc = new ShippingCalculator();
@Test
void bigOrder() {
calc.cost(new Order(120, true));
}
@Test
void smallOrder() {
assertTrue(calc.cost(new Order(50, true)) > 0);
}
@Test
void standardOrder() {
assertTrue(calc.cost(new Order(100, false)) < 10);
}
}To test a proofreader, hire an editor to plant typos on purpose. Say the editor plants ten, in a chapter that was otherwise clean. The proofreader reads the chapter and flags seven of them. Seven of ten caught: a score of 70 percent. The three misses matter: those are mistakes a real reader would have seen, and nobody noticed they were wrong.
But careful. If the editor changes colour to color in a book that allows both, nothing is wrong. Nobody could catch it, and nobody should. Hold on to both ideas: planted faults, and the ones that change nothing. PIT does exactly this to your code.
A mutant is a copy of your code with one small fault in it. PIT makes mutants by editing the compiled bytecode, using rules called mutators. Each mutant has exactly one change, and PIT makes many of them. They are tested one at a time, so every result points at a single spot in your code.
| Mutator | What it does |
|---|---|
CONDITIONALS_BOUNDARY | swaps < with <=, <= with <, > with >=, and >= with > |
NEGATE_CONDITIONALS | flips each comparison to its opposite (== to !=, < to >=, <= to >, …) |
MATH | replaces a binary arithmetic operator with another one, such as + with - |
PRIMITIVE_RETURNS | replaces a returned int, short, long, char, float or double with 0 |
These four, with INCREMENTS, INVERT_NEGS, VOID_METHOD_CALLS, EMPTY_RETURNS, FALSE_RETURNS,
TRUE_RETURNS and NULL_RETURNS, make up the DEFAULTS group.
For each mutant, PIT first finds the tests that run that code (it does a line coverage analysis first and uses it, with test timings, to pick the tests). It runs only those tests, and a test that fails kills the mutant.
A mutant can end four ways:
| Result | Meaning |
|---|---|
| Killed | a test caught the mutation |
| Survived | the tests that ran it passed |
| No coverage | like survived, but no test ran that line |
| Timed out | the mutant made the tests run forever (for example, it removed a loop’s increment) |
The mutation score is the share of all mutants that were killed. Test strength is similar, but it leaves out mutants that no test reached: it asks “when the tests did run the code, how often did they notice?”, and is killed / (killed + survived). The score also punishes code that no test touches at all.
For example, say a class gets twenty mutants. Twelve are killed, three survive and five had no coverage. The score is 12 of 20, 60 percent. Test strength is 12 of 15, 80 percent.
Setting up PIT in Gradle takes one plugin and a pitest block. Tell it which classes to mutate, how
many threads to use, and that your tests are JUnit 5.
plugins {
java
id("info.solidsoft.pitest") version "1.19.0"
}
pitest {
junit5PluginVersion = "1.2.3"
targetClasses = setOf("com.example.shipping.*")
threads = 4
timestampedReports = false
}PIT needs a plugin to run JUnit 5 tests, and the junit5PluginVersion line adds it for you: it adds
the dependency org.pitest:pitest-junit5-plugin and sets the plugin’s testPlugin to junit5. The
version has to match your JUnit version (more on that in the pitfalls).
Run the pitest task with gradle pitest. With timestampedReports off, the HTML report is in
build/reports/pitest.
Maven has one extra moving part: the JUnit 5 plugin goes inside the PIT plugin declaration, because it must be on the classpath of PIT itself, not of your project.
<plugin>
<groupId>org.pitest</groupId>
<artifactId>pitest-maven</artifactId>
<version>1.22.1</version>
<dependencies>
<dependency>
<groupId>org.pitest</groupId>
<artifactId>pitest-junit5-plugin</artifactId>
<version>1.2.3</version>
</dependency>
</dependencies>
<configuration>
<targetClasses>
<param>com.example.shipping.*</param>
</targetClasses>
</configuration>
</plugin>Run it with mvn test-compile org.pitest:pitest-maven:mutationCoverage; the HTML report is written
to target/pit-reports/YYYYMMDDHHMI. (Check Maven Central for current versions, and keep the
pitest-maven version in step with the PIT version you are using.)
Here is a simplified report for the shipping method. Each line shows its mutants. Green means the tests
killed every mutant there. In our method, with the default mutators and only ShippingCalculator
as the target class, a hand count gives five mutants (your report may differ slightly in detail;
the video draws a stylised report in the same spirit):
| # | Mutator | The change | Result |
|---|---|---|---|
| M1 | CONDITIONALS_BOUNDARY | >= becomes > | survived |
| M2 | NEGATE_CONDITIONALS | >= becomes < | survived |
| M3 | NEGATE_CONDITIONALS | order.express() negated | killed by standardOrder |
| M4 | MATH | shipping += 15 becomes shipping -= 15 | killed by smallOrder |
| M5 | PRIMITIVE_RETURNS | return shipping becomes return 0 | killed by smallOrder |
This is a simplified example report: a real PIT run may list a few more mutants than this hand count.
Three of the five mutants were killed: a mutation score of 3 of 5, 60 percent. Coverage said a hundred percent, twice.
Why do M1 and M2 survive? With the > mutant, the order of exactly 100 pays the flat rate, 7.99,
and standardOrder only checks that the cost is below ten. With the < mutant, smallOrder gets 0
plus 15, which is above zero, and bigOrder checks nothing. Notice what did the killing: the weak
checks, above zero and below ten, caught some. Nothing checked what happens at exactly a hundred.
Survivors are the useful rows. Killed mutants say your tests work. Survivors say where they don’t.
A survivor is a question. What should the answer be, exactly at the boundary? An order of exactly a hundred should ship free. So write that test.
@Test
void exactlyAHundredShipsFree() {
assertEquals(0.0, calc.cost(new Order(100, false)));
}Run PIT again. Both survivors now return the flat rate instead of zero, so the new test fails, and both mutants are killed. Five of five: a score of 100 percent. The fix was one test, with one real assertion.
Why did the old suite miss it? Its checks only asked for ranges, above zero and below ten. A boundary needs an exact value.
Coverage asks one question: did this code run? Mutation testing asks another: would the tests notice if this code were wrong? They are not rivals. A line no test runs can only ever score no coverage, so get coverage first. Then mutation testing tells you whether that coverage means anything. Take our suite: coverage said a hundred percent, twice; mutation testing said sixty.
| Code coverage | Mutation testing | |
|---|---|---|
| Question | did this code run? | would the tests notice if it were wrong? |
| Counts | lines, branches, … that executed | mutants that were killed |
| Blind to | whether anything was checked | equivalent mutants (false alarms) |
| Cost | cheap (one test run) | many test runs |
| Tool in this series | JaCoCo | PIT |
mutators parameter replaces the default set, so only do
it on purpose.targetClasses at your core logic. Pricing rules deserve mutation testing. Generated
code and plain data holders don’t.-DwithHistory stores the history in the temp directory, or set
historyInputFile and historyOutputFile. In Gradle, turn on default incremental analysis:pitest {
enableDefaultIncrementalAnalysis = true
}It is marked experimental, and it can miss changes in dependencies (PIT only considers the
strongest ones, such as superclasses and outer classes), so run a full analysis now and then.
Gradle also has historyInputLocation and historyOutputLocation for explicit files.
4. Read every survivor as a missing assertion. Ask what answer the test should have checked.
5. Run it in your pipeline, on a schedule or on pull requests, not on every local build. A good
first step: one package, one run, and every survivor read by a person.
i >= 1 to i > 1
when i is 2: nothing differs, and no test could ever tell. Judge each survivor: is it a missing
check, or a change that changes nothing? Only the first needs a test. PIT helps a little: it
avoids mutating logging calls by default, and its return mutators skip methods that already
return that value.mutationThreshold) fails builds for no good reason. The PIT docs themselves warn that
equivalent mutations affect the choice of threshold.timeoutFactor (default 1.25) and timeoutConstant in Maven (default
4000 ms), timeoutFactor and timeoutConstInMillis in Gradle.NoSuchMethodError as one example).Mutation testing is the wrong tool in an early prototype, where the code changes daily and tests are rewritten with it; on generated code; and in a codebase with no tests yet, where coverage comes first. Everywhere else: plant a bug, count the catches, and read the survivors.
Coverage asks if it ran. Mutation testing asks if anyone would notice.
Use both. Measure what ran with JaCoCo, then break it on purpose with PIT to see what was checked.