QA and Test Automation · Lab 8 of 35

Mutation Testing With PIT and mutmut: Find Weak Tests (Lab)

Measure how good tests really are: run mutation testing on ShopRung's pricing rules. Tests with 89% line coverage kill only 45 of 71 mutants; read the survivors, write the missing boundary tests, and reach 70 of 71. Then learn what an equivalent mutant is.

⏱ 50 minIntermediate💸 Free7 stepsJava + Python

Java 21 + Maven + JUnit 5.11 + PIT 1.17Python 3.12 + pytest + mutmut 3.9 (second path; macOS, Linux or WSL)

Overview video

1 / 6

0 of 7 steps done

What you will build

ShopRung's pricing rules from lab 4 with two versions of their tests, and the mutation reports that tell them apart:

  • The first tests: 5 tests, all green, 89% line coverage. Mutation testing shows they kill only 45 of 71 mutants (63%): changing >= to > on free shipping, or > to >= on the coupon expiry, goes unnoticed.
  • The improved tests: every rule checked on both sides of its edge. They kill 70 of 71. The last one is an equivalent mutant: a change that can never alter the result, so no test can kill it.

Java uses PIT, the standard mutation tool for the JVM, with an HTML report; Python uses mutmut.

Before you start

Setup

S1Java 21 and Maven, or Python 3.12

Python path: mutmut 3 runs on macOS and Linux. On Windows, use WSL (Windows Subsystem for Linux).

Run
java -version
mvn -v
# or
python3 --version

S2Make the project

Java: Maven folders. Python: a src/shop package, tests, and a virtual environment.

Run
# Java
mkdir -p shoprung-pricing/src/main/java/dev/algorung/shop shoprung-pricing/src/test/java/dev/algorung/shop
# Python
mkdir -p shoprung-pricing-py/src/shop shoprung-pricing-py/tests && cd shoprung-pricing-py && python3 -m venv .venv && source .venv/bin/activate
1

The project, PIT and the pricing rules

A build with the mutation tool configured, and the code to mutate.

Mutation testing makes many small changes to your code, one at a time (each one is a mutant): >= becomes >, + becomes -, a return value becomes 0. For each mutant it runs your tests. If a test fails, the mutant is killed: your tests noticed. If all tests still pass, it survived: your tests would not notice that bug.

Java: pom.xml adds the PIT Maven plugin with its JUnit 5 plugin, set to mutate dev.algorung.shop and run the tests in the same package. Copy Pricing.java and Coupon.java from lab 4.

Python: pyproject.toml tells pytest where the code is and tells mutmut what to mutate. Copy pricing.py from lab 4 into src/shop.

pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>dev.algorung</groupId>
  <artifactId>shoprung-pricing</artifactId>
  <version>0.1.0</version>

  <properties>
    <maven.compiler.release>21</maven.compiler.release>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <junit.version>5.11.4</junit.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>org.junit.jupiter</groupId>
      <artifactId>junit-jupiter</artifactId>
      <version>${junit.version}</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

  <build>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.13.0</version>
      </plugin>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.5.2</version>
      </plugin>
      <!-- PIT: mutation testing. Run with: mvn test-compile org.pitest:pitest-maven:mutationCoverage -->
      <plugin>
        <groupId>org.pitest</groupId>
        <artifactId>pitest-maven</artifactId>
        <version>1.17.4</version>
        <dependencies>
          <dependency>
            <groupId>org.pitest</groupId>
            <artifactId>pitest-junit5-plugin</artifactId>
            <version>1.2.1</version>
          </dependency>
        </dependencies>
        <configuration>
          <targetClasses>
            <param>dev.algorung.shop.*</param>
          </targetClasses>
          <targetTests>
            <param>dev.algorung.shop.*</param>
          </targetTests>
          <outputFormats>
            <param>HTML</param>
          </outputFormats>
          <timestampedReports>false</timestampedReports>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>
  1. PIT: the standard mutation testing tool for Java.line 40
  2. Lets PIT run JUnit 5 tests.line 45
  3. Which code to mutate: never your tests.line 50
src/main/java/dev/algorung/shop/Pricing.java
package dev.algorung.shop;

import java.time.LocalDate;

/**
 * ShopRung's money rules (requirements PRICE-1 to PRICE-10), as plain Java.
 * Every amount is whole cents in a long: $50.00 is 5000. No double, so no rounding surprises.
 */
public final class Pricing {
    public static final long FREE_SHIPPING_FROM = 7_500; // $75.00, after the discount
    public static final long SHIPPING = 499;             // $4.99

    /** The four numbers a cart shows. */
    public record Totals(long subtotal, long discount, long shipping, long total) {}

    private Pricing() {}

    /** 1250 becomes "$12.50" (PRICE-1). */
    public static String money(long cents) {
        if (cents < 0) throw new IllegalArgumentException("cents must not be negative: " + cents);
        return String.format("$%d.%02d", cents / 100, cents % 100);
    }

    /** $4.99, or free from $75.00 after the discount (PRICE-9). An empty cart ships nothing. */
    public static long shipping(long afterDiscount) {
        if (afterDiscount == 0) return 0;
        return afterDiscount >= FREE_SHIPPING_FROM ? 0 : SHIPPING;
    }

    /** Subtotal, discount, shipping and total (PRICE-10). A coupon that does not apply gives no discount (PRICE-8). */
    public static Totals totals(long subtotal, Coupon coupon, LocalDate today) {
        if (subtotal < 0) throw new IllegalArgumentException("subtotal must not be negative: " + subtotal);
        long discount = 0;
        if (coupon != null && coupon.problem(subtotal, today) == null) discount = coupon.discount(subtotal);
        long shipping = shipping(subtotal - discount);
        return new Totals(subtotal, discount, shipping, subtotal - discount + shipping);
    }
}
  1. A boundary. PIT will try > here.line 27
src/main/java/dev/algorung/shop/Coupon.java
package dev.algorung.shop;

import java.time.LocalDate;
import java.util.Locale;

/** ShopRung's three coupons (PRICE-2 to PRICE-7), with the same rules and messages as the shop. */
public enum Coupon {
    SAVE10(true, 10, 5_000, null),                       // 10% off from $50.00
    FLAT5(false, 500, 2_000, null),                      // $5.00 off from $20.00
    WELCOME15(true, 15, 0, LocalDate.of(2025, 12, 31));  // expired

    private final boolean percent;
    private final long amount;      // a percent, or cents
    private final long minSubtotal; // cents
    private final LocalDate expiresOn;

    Coupon(boolean percent, long amount, long minSubtotal, LocalDate expiresOn) {
        this.percent = percent;
        this.amount = amount;
        this.minSubtotal = minSubtotal;
        this.expiresOn = expiresOn;
    }

    /** Finds a coupon by code. Codes are not case-sensitive (PRICE-2); an unknown code is refused (PRICE-7). */
    public static Coupon of(String code) {
        String c = code == null ? "" : code.trim().toUpperCase(Locale.ROOT);
        for (Coupon coupon : values()) {
            if (coupon.name().equals(c)) return coupon;
        }
        throw new IllegalArgumentException("No coupon called " + (c.isEmpty() ? "(empty)" : c));
    }

    /** Why this coupon cannot be used, or null when it can. */
    public String problem(long subtotal, LocalDate today) {
        if (expiresOn != null && today.isAfter(expiresOn)) return "This coupon has expired";
        if (subtotal < minSubtotal) return "This coupon needs a subtotal of at least " + Pricing.money(minSubtotal);
        return null;
    }

    /** The discount in cents. A percentage rounds to the nearest cent, half a cent up (PRICE-6). */
    public long discount(long subtotal) {
        if (percent) return (subtotal * amount + 50) / 100;
        return Math.min(amount, subtotal); // a fixed amount never makes the total negative
    }
}
  1. Another boundary: is the last day valid?line 35
2

The first tests: green, and good coverage

Five tests that pass and cover most lines.

Create the test file below. It looks like many real test files: one test per function, each checking a typical value. Run it, and in Python also measure line coverage: 89%. By the usual standard this code is well tested.

Look closer before moving on: every value is far from an edge. Shipping is tested at $10.00 and $100.00, never at $75.00. SAVE10 at $100.00, never at $50.00.

src/test/java/dev/algorung/shop/PricingTest.java
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertEquals;

import java.time.LocalDate;
import org.junit.jupiter.api.Test;

/** The first tests: they pass, and coverage looks great. Are they any good? */
class PricingTest {
    static final LocalDate TODAY = LocalDate.of(2026, 11, 30);

    @Test
    void money() {
        assertEquals("$12.50", Pricing.money(1250));
    }

    @Test
    void shipping() {
        assertEquals(499, Pricing.shipping(1000));
        assertEquals(0, Pricing.shipping(10000));
    }

    @Test
    void save10() {
        assertEquals(9000, Pricing.totals(10000, Coupon.of("SAVE10"), TODAY).total());
    }

    @Test
    void flat5() {
        assertEquals(500, Pricing.totals(3000, Coupon.of("FLAT5"), TODAY).discount());
    }

    @Test
    void expiredCoupon() {
        assertEquals(0, Pricing.totals(10000, Coupon.of("WELCOME15"), TODAY).discount());
    }
}
  1. Typical values: nowhere near the $75.00 edge.line 19
  2. $100.00: far above the $50.00 minimum.line 25
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Tests run: 5, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
3

Run mutation testing

The real quality of the first tests: 45 of 71 mutants killed.

Run the mutation tool. It creates every mutant, runs the tests against each, and counts. This takes longer than a normal test run (seconds here, minutes on real projects), because the tests run once per mutant.

Python, real result: 71 mutants, 45 killed, 26 survived. A mutation score of 63%, from tests with 89% line coverage. Java: PIT prints a summary like the one below and writes an HTML report to target/pit-reports/index.html, where each line of code shows which mutants survived. Your exact Java numbers differ from Python's, because PIT makes different kinds of changes than mutmut.

Coverage only says a line ran during a test. Mutation testing asks whether any test would notice if that line were wrong.

Run
mvn test-compile org.pitest:pitest-maven:mutationCoverage
You should seeyour text will differ: the model writes it
================================================================================
- Statistics
================================================================================
>> Line Coverage (for mutated classes only): .../... (..%)
>> Generated .. mutations Killed .. (..%)
...
[INFO] BUILD SUCCESS
4

Read the survivors

Turn each surviving mutant into a missing test case.

Each survivor is a bug your tests would let through. List them and look at a few. In Python, mutmut results lists the survivors and mutmut show <name> prints one as a diff; in Java, open the HTML report and click a class. These are real survivors from the first tests:

# free shipping from exactly $75.00
-    return 0 if after_discount >= FREE_SHIPPING_FROM else SHIPPING
+    return 0 if after_discount > FREE_SHIPPING_FROM else SHIPPING

# WELCOME15 is still valid on its last day
-    if c.expires_on and today > c.expires_on:
+    if c.expires_on and today >= c.expires_on:

# $0.00 is a valid amount
-    if cents < 0:
+    if cents <= 0:

# an empty or missing code
-    c = (code or "").strip().upper()
+    c = (code or "XXXX").strip().upper()

# the error message is never checked
-        raise ValueError(f"cents must not be negative: {cents}")
+        raise ValueError(None)

Each one names a test you did not write: shipping at exactly 7500, the coupon on 31 December 2025 and 1 January 2026, money(0), an empty coupon code, the exact error text. This is boundary value analysis, pointed at by a tool.

5

Kill them: tests on both sides of every edge

A test file where every rule is checked exactly on its boundaries.

Replace the test file. Each group comes from the survivors:

  • money: 0, 5 and 100 cents, and the exact error for -1.
  • shipping: 0, 1, 7499, 7500 and 7501.
  • coupon codes: lower case, surrounding spaces, unknown, empty and missing, with the exact messages.
  • SAVE10: 4999 refused, 5000 accepted. WELCOME15: valid on 31 December 2025, expired on 1 January 2026.
  • discounts: half a cent rounds up (7495 → 750), less rounds down (7494 → 749), FLAT5 never goes below zero.
  • totals: each path through the function, including an expired coupon and an empty cart, and the error for a negative subtotal.
src/test/java/dev/algorung/shop/PricingTest.java
package dev.algorung.shop;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

import dev.algorung.shop.Pricing.Totals;
import java.time.LocalDate;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

/** The tests after mutation testing: every rule checked on both sides of its edge. */
class PricingTest {
    static final LocalDate TODAY = LocalDate.of(2026, 11, 30);

    @ParameterizedTest
    @CsvSource({"1250, $12.50", "5, $0.05", "0, $0.00", "100, $1.00"})
    void money(long cents, String shown) {
        assertEquals(shown, Pricing.money(cents));
    }

    @Test
    void moneyRefusesNegativeAmounts() {
        var e = assertThrows(IllegalArgumentException.class, () -> Pricing.money(-1));
        assertEquals("cents must not be negative: -1", e.getMessage());
    }

    @ParameterizedTest(name = "{0} cents after the discount -> shipping {1}")
    @CsvSource({"0, 0", "1, 499", "7499, 499", "7500, 0", "7501, 0"})
    void shippingIsFreeFrom75Dollars(long afterDiscount, long expected) {
        assertEquals(expected, Pricing.shipping(afterDiscount));
    }

    @ParameterizedTest
    @CsvSource({"SAVE10", "save10", "' Save10 '"})
    void codesAreNotCaseSensitiveAndTrimmed(String code) {
        assertEquals(Coupon.SAVE10, Coupon.of(code));
    }

    @ParameterizedTest
    @CsvSource(value = {"NOPE, No coupon called NOPE", "'', No coupon called (empty)", "NULL, No coupon called (empty)"},
               nullValues = "NULL")
    void unknownCouponsAreRefused(String code, String message) {
        var e = assertThrows(IllegalArgumentException.class, () -> Coupon.of(code));
        assertEquals(message, e.getMessage());
    }

    @Test
    void save10NeedsExactly50Dollars() {
        assertEquals("This coupon needs a subtotal of at least $50.00", Coupon.SAVE10.problem(4_999, TODAY));
        assertNull(Coupon.SAVE10.problem(5_000, TODAY));
    }

    @Test
    void welcome15WorksOnItsLastDayAndNotTheDayAfter() {
        assertNull(Coupon.WELCOME15.problem(4_000, LocalDate.of(2025, 12, 31)));
        assertEquals("This coupon has expired", Coupon.WELCOME15.problem(4_000, LocalDate.of(2026, 1, 1)));
    }

    @ParameterizedTest(name = "{0} on {1} cents -> {2}")
    @CsvSource({
        "SAVE10, 5000, 500",
        "SAVE10, 7495, 750",  // 749.5 cents: half a cent rounds up
        "SAVE10, 7494, 749",  // 749.4 cents: rounds down
        "FLAT5,  2000, 500",
        "FLAT5,   300, 300",  // a fixed amount never makes the total negative
    })
    void discounts(String code, long subtotal, long expected) {
        assertEquals(expected, Coupon.of(code).discount(subtotal));
    }

    @ParameterizedTest(name = "{0} cents with {1} -> {2} off, {3} shipping, {4} total")
    @CsvSource(value = {
        "5000, SAVE10,    500, 499, 4999",
        "4999, SAVE10,      0, 499, 5498",  // just below: no discount
        "8400, SAVE10,    840,   0, 7560",  // free shipping after the discount
        "8300, SAVE10,    830, 499, 7969",  // 7470 after the discount: shipping charged
        "2000, NULL,        0, 499, 2499",
        "4000, WELCOME15,   0, 499, 4499",  // expired on TODAY: no discount
        "0,    NULL,        0,   0,    0",  // an empty cart costs nothing
    }, nullValues = "NULL")
    void totals(long subtotal, String code, long discount, long shipping, long total) {
        Totals t = Pricing.totals(subtotal, code == null ? null : Coupon.of(code), TODAY);
        assertEquals(new Totals(subtotal, discount, shipping, total), t);
    }

    @Test
    void totalsRefuseNegativeSubtotals() {
        var e = assertThrows(IllegalArgumentException.class, () -> Pricing.totals(-1, null, TODAY));
        assertEquals("subtotal must not be negative: -1", e.getMessage());
    }
}
  1. Kills >= → > on free shipping.line 30
  2. The last valid day, and the day after: kills mutants on the expiry check.line 57
  3. Exactly half a cent: checks the rounding direction.line 64
  4. Checking the message kills mutants that change it.line 26
  5. The empty cart: kills < → <= on the subtotal check.line 81
Run
mvn test
You should seeyour text will differ: the model writes it
[INFO] Tests run: 31, Failures: 0, Errors: 0, Skipped: 0
[INFO] BUILD SUCCESS
6

Run it again, and meet an equivalent mutant

70 of 71 killed, and a survivor that cannot be killed.

Run mutation testing again. Python: 70 of 71 killed. One survivor is left:

-        return (subtotal * c.amount + 50) // 100
+        return (subtotal * c.amount + 51) // 100

Try to write a test that kills it, and you cannot. For +51 to round differently from +50, subtotal × percent would have to end in 49. ShopRung's percentages are 10 and 15, so that product always ends in 0 or 5. No input can ever show the difference. This is an equivalent mutant: the code changed, but its behaviour did not. Every mutation tool produces some; you note them and move on. That is why teams aim for a high mutation score, not 100%.

Run
mvn test-compile org.pitest:pitest-maven:mutationCoverage
open target/pit-reports/index.html
You should seeyour text will differ: the model writes it
>> Generated .. mutations Killed .. (9.%)
...
[INFO] BUILD SUCCESS
7

Using mutation testing at work

Where it pays off, and how to keep it affordable.

  • Pick the code: business rules like pricing, permissions and calculations, where a small mistake costs money. Not glue code or UI.
  • Run it incrementally: PIT has an incremental mode and a Git integration that mutates only changed code; mutmut caches results. Full runs nightly, changed code per pull request.
  • Use the score as a signal, not a target: a falling score on a pull request means new code arrived without real tests. Reviewers open the report instead of arguing about coverage.
  • In interviews and reviews, mutation testing is the clearest answer to "coverage is 90%, but are the tests good?".

Check it works

Compare the two runs. With the first tests, many mutants survive (Python: 45 of 71 killed). With the improved tests, all but the equivalent mutant are killed (Python: 70 of 71). If a mutant you expected to kill still survives, mutmut show or the PIT report tells you which line and which change: write the test that would notice it.

Test
mvn test-compile org.pitest:pitest-maven:mutationCoverage
# or: mutmut run
You should see
71/71  🎉 70 🫥 0  ⏰ 0  🤔 0  🙁 1  🔇 0  🧙 0

Troubleshooting

PIT: No mutations found.

targetClasses does not match your package. It must be dev.algorung.shop.* (or your own package).

PIT: tests are not found or the run fails at the start.

Run mvn test first: PIT needs a green suite. Check the pitest-junit5-plugin dependency is inside the PIT plugin, not in the project's dependencies.

mutmut: "Running forced fail test" fails.

mutmut checks the tests can fail at all. Run pytest alone first and fix any import error (the pythonpath = ["src"] line).

mutmut on Windows.

mutmut 3 needs a Unix-like system. Use WSL, or take the Java path.

Mutation testing takes too long.

Limit it to the classes that matter (targetClasses, source_paths), keep unit tests fast, and run full mutation tests nightly.

What changes in production

  • Teams apply mutation testing to critical business logic, not the whole codebase.
  • PIT runs incrementally on changed code in pull requests; full runs happen nightly, with the HTML report as a CI artifact.
  • Survivors become review comments ("this boundary is untested"), and equivalent mutants are noted and excluded.
  • Mutation score complements coverage: coverage finds code no test runs, mutation testing finds code no test really checks.

Interview angle

“Coverage is 90%. How do you know whether the tests are any good?”

Coverage only shows lines were executed. Mutation testing shows whether tests notice changes: a tool like PIT or mutmut makes small changes such as >= to >, runs the tests against each, and reports which mutants survived. Each survivor is a missing assertion or boundary case. On pricing rules I have seen 89% line coverage kill only 63% of mutants; adding boundary tests at the exact edges took it to all but one, which was an equivalent mutant that cannot change behaviour. I run it on critical logic, incrementally in CI.

Practice

These run in your browser and check your answer.

Kill the mutant

This shipping function is correct. A mutation tool changed >= to >, and the tests below the starter did not notice. Write kills_mutant() so it returns True only if the given function behaves correctly at the edge: call it with 7500 and check the result is 0.

Exercise
def kills_mutant(shipping):
    # this check is too far from the edge to notice the mutant
    return shipping(10_000) == 0
Hint

Test exactly at the boundary: shipping(7_500).

The full project

Every file from this lab, as it is after the last step.

Download Java project (.zip) Download Python project (.zip)