読み物Testing

Level: Pro

Advanced Testing Techniques: Property-Based Testing, Fuzzing, and Mutation Testing

Let the computer find bugs: generated inputs that check properties, coverage-guided fuzzing, and mutation testing that checks your tests, with a real bug found and a gap that 100% coverage hid.

Edeeson Opina9 min read

A Pro lesson card: lesson 13 of the Software Testing & Quality Engineering series, Advanced Testing Techniques: Property-Based Testing, Fuzzing, and Mutation Testing, with the Miso fox walking.

What you’ll learn

  • Write properties: invariants, round trips, idempotence, and models
  • Build realistic generators and reproduce failures from seeds
  • Explain coverage-guided fuzzing and when to use it
  • Use mutation testing to find weak tests
On this page
  1. Before you start
  2. Property-based testing
  3. A bug found by generated input
  4. Replaying a failure
  5. Generators matter
  6. Fuzzing
  7. Mutation testing: testing your tests
  8. Using mutation testing well
  9. Choosing a technique
  10. Common mistakes and troubleshooting
  11. Practical exercise: let the computer find bugs
  12. Key takeaways
  13. References
  14. What's next

Every test so far has used examples someone chose. Chosen examples find the bugs you can imagine; the rest wait for users. This lesson covers three techniques that look for what you didn't imagine, and one that checks your tests themselves. Property-based testing generates hundreds of inputs and checks rules that must always hold. Fuzzing throws massive amounts of unexpected input at code to find crashes. Mutation testing deliberately plants bugs in your code to see whether your tests notice. Each example below shows real output, including a bug found by generated input and a gap that 100% code coverage hid.

Before you start

You should be comfortable with Vitest and test design from the earlier lessons, especially boundary values (lesson 3) and coverage (lesson 6), and have finished Accessibility, Cross-Browser, and Cross-Platform Testing. Examples use TypeScript with fast-check and Stryker; Rust equivalents are mentioned.

Property-based testing

Instead of writing "input A gives output B," you describe a property: a rule that should hold for *every* valid input. The tool generates many inputs, checks the property against each, and if one fails, shrinks it to the smallest input that still fails.

Good properties come from a few patterns:

  • Invariants: the output always has some shape. A slug is always lowercase letters, digits, and single dashes.
  • Round trips: decoding what you encoded gives the original. parse(format(x)) equals x.
  • Idempotence: doing it twice equals doing it once. slugify(slugify(t)) equals slugify(t).
  • Comparison with a simple model: an optimized function agrees with a slow, obviously correct one.
  • Conservation: nothing is lost. Splitting a bill gives parts that add up to the total.

A bug found by generated input

A function creates URL slugs of at most 20 characters:

src/slug.tsTypeScript
/** A URL slug of at most 20 characters: lowercase letters and digits joined by single dashes. */
export function slugify(title: string): string {
  return title
    .toLowerCase()
    .replace(/[^a-z0-9]+/g, "-")
    .replace(/^-|-$/g, "")
    .slice(0, 20);
}

The example test ("Miso Soup: 3 Ways!" becomes "miso-soup-3-ways") passes. The property test with fast-check describes what must *always* be true, using a generator that produces title-like strings (a few words separated by spaces and punctuation):

src/slug.test.tsTypeScript
import fc from "fast-check";
import { describe, expect, it } from "vitest";
import { slugify } from "./slug";

// Titles: a few lowercase words separated by spaces or punctuation.
const titles = fc
  .array(fc.stringMatching(/^[a-z0-9]{1,8}$/), { minLength: 1, maxLength: 6 })
  .chain((words) => fc.constantFrom(" ", ": ", " - ", "!  ").map((separator) => words.join(separator)));

describe("slugify", () => {
  it("always returns a valid slug of at most 20 characters (property)", () => {
    fc.assert(
      fc.property(titles, (title) => {
        const slug = slugify(title);
        expect(slug.length).toBeLessThanOrEqual(20);
        expect(slug).toMatch(/^([a-z0-9]+(-[a-z0-9]+)*)?$/);
      }),
    );
  });
});
Text
   × slugify > always returns a valid slug of at most 20 characters (property)
     → Property failed after 22 tests
{ seed: -2049675838, path: "21:2:1:7:9:9:6:11:13:16:21:23:24:24:27:28:29:29:29:29:29", endOnFailure: true }
Counterexample: ["0 a0a aaa0aa00 000a a"]
Shrunk 20 time(s)

Caused by: AssertionError: expected '0-a0a-aaa0aa00-000a-' to match /^([a-z0-9]+(-[a-z0-9]+)*)?$/

After 22 generated titles, fast-check found one that produced "0-a0a-aaa0aa00-000a-": a slug ending in a dash. The defect: the code trims dashes *before* cutting to 20 characters, so the cut can land right after a dash. Nobody writing examples by hand would likely pick a title whose 20th character is a separator.

The output also includes a seed and path. Passing them back to fc.assert replays exactly this failure, which makes it reproducible in a regression test.

The fix is to cut first, then trim:

src/slug.tsTypeScript
return title
  .toLowerCase()
  .replace(/[^a-z0-9]+/g, "-")
  .slice(0, 20)
  .replace(/^-+|-+$/g, "");
Text
 ✓ src/slug.test.ts (2 tests) 16ms
      Tests  2 passed (2)

Replaying a failure

The seed and path make a failure reproducible, so it can become a permanent regression check while you fix the bug:

TypeScript
fc.assert(
  fc.property(titles, (title) => {
    const slug = slugify(title);
    expect(slug).toMatch(/^([a-z0-9]+(-[a-z0-9]+)*)?$/);
  }),
  { seed: -2049675838, path: "21:2:1:7:9:9:6:11:13:16:21:23:24:24:27:28:29:29:29:29:29", endOnFailure: true },
);

Run against the original code, this replays the same counterexample, "0 a0a aaa0aa00 000a a", every time; against the fixed code, it passes. Once fixed, also add the shrunk counterexample as an ordinary example test, expect(slugify("0 a0a aaa0aa00 000a a")).toBe("0-a0a-aaa0aa00-000a"), so the case stays documented even if the generator changes later.

Generators matter

A first version of this test used fc.string(), arbitrary short strings. It passed, because random strings rarely contain enough letters to reach 20 characters, so the slicing code was hardly exercised. Property tests are only as good as their generators: produce inputs that resemble real data, including the awkward parts.

In Rust, proptest and quickcheck provide the same approach; PHP has libraries such as Eris; Python has Hypothesis.

Fuzzing

Fuzzing feeds a program huge numbers of unexpected, often malformed inputs to find crashes, hangs, memory errors, and failed internal assertions. Modern fuzzers are coverage-guided: they observe which code paths each input exercises and mutate interesting inputs to reach new paths, which lets them find deep bugs in parsers and decoders that random input never would.

Fuzzing differs from property-based testing in emphasis: it runs for minutes to days, usually checks "doesn't crash or violate assertions" rather than rich properties, and is especially valuable for code that parses untrusted input: file formats, network protocols, query strings, image decoders.

In Rust, cargo-fuzz uses libFuzzer. It currently requires a nightly toolchain, because it relies on unstable compiler instrumentation:

Shell
cargo install cargo-fuzz
cargo +nightly fuzz init
cargo +nightly fuzz run parse_recipe

A fuzz target is a function that receives arbitrary bytes:

fuzz/fuzz_targets/parse_recipe.rsRUST
#![no_main]
use libfuzzer_sys::fuzz_target;

fuzz_target!(|data: &[u8]| {
    if let Ok(text) = std::str::from_utf8(data) {
        // Must never panic, whatever the input; errors are fine, crashes are bugs.
        let _ = recipes::parse_recipe(text);
    }
});

When the fuzzer finds an input that crashes, it saves it to a file. Turn that file into a regular regression test, fix the bug, and keep fuzzing. Other ecosystems have equivalents: Go has built-in fuzzing (go test -fuzz), Python has Atheris, JavaScript has Jazzer.js, and projects can join OSS-Fuzz for continuous fuzzing of open-source code.

Fuzz only your own code and systems you're authorized to test. Pointing a fuzzer at someone else's running service is an attack.

Mutation testing: testing your tests

Coverage tells you which code ran during tests. Mutation testing tells you whether the tests would notice if that code were wrong. A mutation tool makes many small changes (mutants) to your code, such as > to >=, && to ||, + to -, a return true to return false, and runs your tests against each. If a test fails, the mutant is killed: your tests detected the planted bug. If all tests pass, the mutant survived: a real bug of that shape would slip through.

The reminder function from lesson 6 had 100% statement, branch, function, and line coverage. Running Stryker on it:

stryker.config.jsonJSON
{
  "testRunner": "vitest",
  "mutate": ["src/reminders.ts"],
  "reporters": ["clear-text"],
  "coverageAnalysis": "perTest"
}
Text
[Survived] EqualityOperator
src/reminders.ts:11:9
-       if (start > now.getTime() && start <= dayAhead) {
+       if (start >= now.getTime() && start <= dayAhead) {

--------------|------------------|----------|-----------|------------|----------|----------|
              | % Mutation score |          |           |            |          |          |
File          |  total | covered | # killed | # timeout | # survived | # no cov | # errors |
--------------|--------|---------|----------|-----------|------------|----------|----------|
All files     |  95.24 |   95.24 |       20 |         0 |          1 |        0 |        0 |
--------------|--------|---------|----------|-----------|------------|----------|----------|

Twenty mutants were killed, but one survived: changing > to >= didn't break any test. That means the behavior for a class starting exactly now is untested. Is a reminder for a class that's starting this very second correct? It doesn't matter which answer is right; what matters is that nobody decided, and no test would catch a change. One boundary test (lesson 3 again) closes the gap:

TypeScript
it("skips a booking that starts right now", async () => {
  expect(await sendReminders([booking("2026-11-01T09:00:00Z")], mailer, at("2026-11-01T09:00:00Z"))).toBe(0);
});
Text
All files     | 100.00 |  100.00 |       21 |         0 |          0 |        0 |        0 |

Using mutation testing well

  • It's slow: it runs the test suite many times. Run it on critical modules, on changed files, or nightly, not on every commit for the whole codebase.
  • Not every surviving mutant is a problem. Some are equivalent mutants that don't change behavior; mark them and move on.
  • Use the mutation score as a guide to where tests are weak, not as a target to maximize.
  • Tools exist for most languages: Stryker (JavaScript, TypeScript, C#, Scala), cargo-mutants (Rust), Infection (PHP), PIT (Java), and mutmut (Python).

Choosing a technique

  • Property-based tests for logic with clear rules: parsers and formatters, calculations, data transformations, state machines.
  • Fuzzing for code that handles untrusted or complex input, especially in memory-unsafe code or where crashes are security issues (lesson 14).
  • Mutation testing for critical modules where you need to trust the tests: pricing, permissions, data integrity.

All three complement example-based tests rather than replacing them. They also cost more to run, so start with the code where a missed bug would hurt most, and expand once the team is comfortable reading their output. Example tests document specific behavior clearly; these techniques search the space around them.

Common mistakes and troubleshooting

  • Weak generators. fc.string() alone rarely produces realistic inputs; build generators that look like your data.
  • Properties that restate the implementation. If the property is the same algorithm, it will share the same bugs. Use invariants, round trips, or a simpler model.
  • Ignoring the seed. Record seeds of failures and turn counterexamples into example tests.
  • Fuzzing only once. Fuzzing finds more over time; run it continuously or on a schedule.
  • Chasing a 100% mutation score. Investigate survivors in important code; accept equivalent mutants.
  • Stryker can't find tests or times out. Check the test runner plugin matches your framework, and that the test command passes on its own first.

Practical exercise: let the computer find bugs

  1. Write a property test for a function in your project using an invariant or a round trip, with a realistic generator.
  2. If it finds a failure, read the shrunk counterexample, fix the bug, and add the counterexample as an example test.
  3. Run a mutation testing tool on one important module. Investigate every surviving mutant and add tests for real gaps.
  4. If you write Rust or another language with fuzzing support, add a fuzz target for a parser and run it for ten minutes on your own machine.
  5. Compare the module's code coverage with its mutation score. What did coverage miss?

Key takeaways

  • Property-based testing checks rules over many generated inputs and shrinks failures to minimal counterexamples.
  • Good properties are invariants, round trips, idempotence, model comparisons, and conservation; good generators resemble real data.
  • Coverage-guided fuzzing finds crashes in code that handles untrusted input; fuzz only what you're authorized to test.
  • Mutation testing plants small bugs to check whether tests notice; it reveals gaps that 100% coverage hides.
  • These techniques complement example-based tests.

References

What's next

Fuzzing is one tool in a broader discipline. Security Testing and Software Supply Chain Verification covers how to test for security problems, safely and with authorization.

See every lesson in Software Testing & Quality Engineering: From Fundamentals to Production-Ready Software