# Mutation Testing with PITA 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](/testing/jacoco-code-coverage/), 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.

{{< lesson-video youtube="UGXrBwIzdMc" title="Mutation Testing with PIT" >}}

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

```java
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.

```java
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.

```mermaid {alt="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." caption="The editor and the proofreader, mapped onto the lesson."}
flowchart LR
  A1["editor"] --> B1["PIT"]
  A2["planted typo"] --> B2["mutant"]
  A3["proofreader"] --> B3["your tests"]
  A4["typo caught"] --> B4["killed"]
  A5["typo missed"] --> B5["survived"]
  A6["colour / color"] --> B6["equivalent mutant"]
  class A1,A2,A3 c4
  class B1,B2,B3 c5
  class A4 good
  class B4 good
  class A5 bad
  class B5 bad
  class A6,B6 warn
```

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

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

```mermaid {alt="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)." caption="One mutant, start to finish."}
flowchart LR
  C["bytecode"] --> M["mutate<br/>one fault"]
  M --> R["run the<br/>covering tests"]
  R --> K["killed"]
  R --> S["survived"]
  class C c1
  class M c4
  class R c5
  class K good
  class S bad
```

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

```kotlin
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.

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

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

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

```java
@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.

```mermaid {alt="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." caption="What to do with a survivor."}
flowchart TD
  S["a surviving mutant"] --> N{"did any test<br/>run that line?"}
  N -->|no| T["write a test<br/>(coverage first)"]
  N -->|yes| Q{"would correct code<br/>behave differently?"}
  Q -->|yes| A["add an assertion<br/>on the exact value"]
  Q -->|no| E["equivalent mutant:<br/>leave it"]
  class S bad
  class T,A good
  class E warn
```

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

```mermaid {alt="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." caption="Two questions, two tools."}
flowchart LR
  subgraph COV["Coverage (JaCoCo)"]
    direction TB
    C1["did it run?"]
  end
  subgraph MUT["Mutation testing (PIT)"]
    direction TB
    M1["would anyone notice?"]
  end
  COV ==>|"first"| MUT
  class C1 c1
  class M1 c5
```

| | 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](/testing/jacoco-code-coverage/) | PIT |

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

```kotlin
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](/testing/jacoco-code-coverage/), then break it on
purpose with PIT to see what was checked.

## References

- PIT: [basic concepts](https://pitest.org/quickstart/basic_concepts/), [mutators](https://pitest.org/quickstart/mutators/), [Maven quickstart](https://pitest.org/quickstart/maven/), [command line options](https://pitest.org/quickstart/commandline/), [incremental analysis](https://pitest.org/quickstart/incremental_analysis/)
- [gradle-pitest-plugin](https://github.com/szpak/gradle-pitest-plugin) (README and changelog)
- [pitest-junit5-plugin](https://github.com/tobiasstadler/pitest-junit5-plugin)
