Mutation Testing with PIT

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.

The same code, the same tests

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);
    }
}

An editor plants typos

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.

The proofreader analogy mapped onto testing: the editor is PIT, the planted typo is a mutant, the proofreader is your test suite, a caught typo is a killed mutant, a missed typo is a survivor, and colour versus color is an equivalent mutant. The proofreader analogy mapped onto testing: the editor is PIT, the planted typo is a mutant, the proofreader is your test suite, a caught typo is a killed mutant, a missed typo is a survivor, and colour versus color is an equivalent mutant.
The editor and the proofreader, mapped onto the lesson.

What a mutant is, and how PIT works

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.

MutatorWhat it does
CONDITIONALS_BOUNDARYswaps < with <=, <= with <, > with >=, and >= with >
NEGATE_CONDITIONALSflips each comparison to its opposite (== to !=, < to >=, <= to >, …)
MATHreplaces a binary arithmetic operator with another one, such as + with -
PRIMITIVE_RETURNSreplaces 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.

Mutation flow: your code's bytecode is mutated with one small fault, PIT picks the tests that cover the mutated code, runs them, and the mutant is either killed (a test failed) or survived (all passed). Mutation flow: your code's bytecode is mutated with one small fault, PIT picks the tests that cover the mutated code, runs them, and the mutant is either killed (a test failed) or survived (all passed).
One mutant, start to finish.

A mutant can end four ways:

ResultMeaning
Killeda test caught the mutation
Survivedthe tests that ran it passed
No coveragelike survived, but no test ran that line
Timed outthe mutant made the tests run forever (for example, it removed a loop’s increment)

The score

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.

Gradle setup

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.)

Reading the report

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):

#MutatorThe changeResult
M1CONDITIONALS_BOUNDARY>= becomes >survived
M2NEGATE_CONDITIONALS>= becomes <survived
M3NEGATE_CONDITIONALSorder.express() negatedkilled by standardOrder
M4MATHshipping += 15 becomes shipping -= 15killed by smallOrder
M5PRIMITIVE_RETURNSreturn shipping becomes return 0killed 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.

The boundary test

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.

What to do with a surviving mutant: first ask whether any test ran the line; if not, write a test (coverage first). If a test ran it, ask whether a correct program would behave differently; if yes, add an assertion that checks the exact value; if no, it is an equivalent mutant and you leave it. What to do with a surviving mutant: first ask whether any test ran the line; if not, write a test (coverage first). If a test ran it, ask whether a correct program would behave differently; if yes, add an assertion that checks the exact value; if no, it is an equivalent mutant and you leave it.
What to do with a survivor.

Coverage versus mutation testing

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.

Two questions side by side: code coverage asks did the code run, answered by JaCoCo; mutation testing asks would the tests notice if the code were wrong, answered by PIT. Coverage comes first. Two questions side by side: code coverage asks did the code run, answered by JaCoCo; mutation testing asks would the tests notice if the code were wrong, answered by PIT. Coverage comes first.
Two questions, two tools.
Code coverageMutation testing
Questiondid this code run?would the tests notice if it were wrong?
Countslines, branches, … that executedmutants that were killed
Blind towhether anything was checkedequivalent mutants (false alarms)
Costcheap (one test run)many test runs
Tool in this seriesJaCoCoPIT

Best practices

  1. Start with the default mutators. They were chosen to make few useless mutants, so the noise stays low. Naming mutators with the mutators parameter replaces the default set, so only do it on purpose.
  2. Point targetClasses at your core logic. Pricing rules deserve mutation testing. Generated code and plain data holders don’t.
  3. Keep it fast with incremental analysis. PIT stores its results in a history file and skips work it can infer. In Maven, -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.

Pitfalls

  1. Treating equivalent mutants as test gaps. Sometimes a survivor isn’t a missing test, because the changed code behaves the same. The PIT docs give the example of changing 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.
  2. Chasing a hundred percent. Equivalent mutants make it unreachable, and a threshold set too high (mutationThreshold) fails builds for no good reason. The PIT docs themselves warn that equivalent mutations affect the choice of threshold.
  3. Timeouts. A mutant that removes a loop counter can loop forever. PIT notices when tests run far longer than usual and reports timed out. The limit is the normal test time times a factor, plus a constant: timeoutFactor (default 1.25) and timeoutConstant in Maven (default 4000 ms), timeoutFactor and timeoutConstInMillis in Gradle.
  4. Mutating everything on every build. Mutants multiply fast, and every one runs tests. Scope it, and schedule it.
  5. Slow or flaky tests. A test that fails at random can look like it killed a mutant, and a slow one drags the whole run.
  6. The JUnit 5 plugin. Its version has to match your JUnit version, or PIT can fail at run time (the plugin’s README lists a NoSuchMethodError as one example).

When not to use it

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.

Recap

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.

References