A passing test tells you the code did what the test checked. It does not tell you the test checks anything important. A test with a missing assertion passes forever, and you only learn it was useless when the bug it should have caught reaches users. Mutation testing turns that around: deliberately introduce a small, realistic bug, called a mutant, and run the tests. If some test fails, the mutant is killed and you have evidence the tests guard that behavior. If every test still passes, the mutant survived, and you have found a gap.
Good mutants imitate real mistakes: a >= that becomes >, a branch that returns the wrong variant, a state write that moves to the wrong place or disappears. For replay behavior, the dangerous mutant is one that applies the amount again but still returns "replayed". A test that checks only the returned string cannot see the difference. Only a check of the stored value can.
Predict and run
Which assertion would catch changing the replay branch to add the amount again?
use std::collections::BTreeMap;
#[derive(Default)]
struct Counter {
value: u32,
receipts: BTreeMap<u32, u32>,
}
impl Counter {
fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(previous) = self.receipts.get(&id) {
return if *previous == amount { Ok("replayed") } else { Err("conflict") };
}
let next = self.value.checked_add(amount).ok_or("overflow")?;
self.value = next;
self.receipts.insert(id, amount);
Ok("applied")
}
}
fn main() {
let mut counter = Counter::default();
assert_eq!(counter.add(7, 5), Ok("applied"));
assert_eq!(counter.add(7, 5), Ok("replayed"));
assert_eq!(counter.value, 5);
assert_eq!(counter.receipts.len(), 1);
println!("Replay checks passed");
}Check your prediction
Replay checks passedOnly assert_eq!(counter.value, 5) would catch it: with the mutant, the value becomes 10 while both returned strings stay correct. Try it. Inside the known-ID branch, add self.value += amount; before the return and run: the program stops with an assertion failure showing left: 10 and right: 5. Restore the original afterward. Editing the code by hand works, but it leaves you one forgotten revert away from shipping the mutant.
Run the tests against the mutant side by side
A safer way to explore is to keep the mutant as a separate function and run each test against both versions. A method like Counter::add can be passed as an ordinary function pointer, so the tests do not care which implementation they receive.
use std::collections::BTreeMap;
#[derive(Default)]
struct Counter {
value: u32,
receipts: BTreeMap<u32, u32>,
}
impl Counter {
fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(previous) = self.receipts.get(&id) {
return if *previous == amount { Ok("replayed") } else { Err("conflict") };
}
let next = self.value.checked_add(amount).ok_or("overflow")?;
self.value = next;
self.receipts.insert(id, amount);
Ok("applied")
}
}
type Add = fn(&mut Counter, u32, u32) -> Result<&'static str, &'static str>;
// The mutant: a replay applies the amount again but still reports "replayed".
fn replay_adds_again(counter: &mut Counter, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(&previous) = counter.receipts.get(&id) {
if previous != amount { return Err("conflict"); }
counter.value += amount;
return Ok("replayed");
}
counter.add(id, amount)
}
fn weak(add: Add) -> bool {
let mut counter = Counter::default();
add(&mut counter, 7, 5) == Ok("applied") && add(&mut counter, 7, 5) == Ok("replayed")
}
fn strong(add: Add) -> bool {
let mut counter = Counter::default();
add(&mut counter, 7, 5) == Ok("applied")
&& add(&mut counter, 7, 5) == Ok("replayed")
&& counter.value == 5
&& counter.receipts.len() == 1
}
fn main() {
let versions: [(&str, Add); 2] = [("original", Counter::add), ("mutant", replay_adds_again)];
for (test_name, test) in [("weak", weak as fn(Add) -> bool), ("strong", strong)] {
for (name, add) in versions {
let verdict = if test(add) { "pass" } else { "FAIL" };
println!("{test_name} test, {name}: {verdict}");
}
}
}weak test, original: pass
weak test, mutant: pass
strong test, original: pass
strong test, mutant: FAILRead the table by rows. Both tests pass the original, which is necessary but tells you nothing about strength. The weak test also passes the mutant: it survived. The strong test kills it. That one line of output is the evidence that the value check earns its place.
The tests return bool here so one program can show all four results. Real tests use assert!, and a mutation run means "this test now fails". The Day 7 project keeps its mutants as find-and-replace pairs in a JSON file, and a browser check applies each one and confirms the ledger checks fail.
When a mutant survives
A surviving mutant means one of two things. Usually the tests are missing an assertion, and you add one. Sometimes the mutant is equivalent: it changes the code without changing any observable behavior, such as writing amount == *previous instead of *previous == amount. No test can kill an equivalent mutant, so do not try. Choose mutants that represent a believable mistake with a visible consequence.
Snapshot everything a failure must preserve
For every rejection path, capture each piece of observable state before the call and compare all of it afterward. Checking only the field you expected the bug to touch is how the next, different bug gets through.
Practice
Your turn
Write conflict_test(add: Add) -> bool. It accepts ID 7 with amount 5, saves the value and a clone of the receipt map, sends ID 7 with amount 8, and returns true only if the result is Err("conflict") and both saved pieces of state are unchanged. Then write a mutant, conflict_overwrites, that stores the new amount in the receipt before returning conflict. Run the test against both versions. Expect original: pass and mutant: FAIL.
use std::collections::BTreeMap;
#[derive(Default)]
struct Counter {
value: u32,
receipts: BTreeMap<u32, u32>,
}
impl Counter {
fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(previous) = self.receipts.get(&id) {
return if *previous == amount { Ok("replayed") } else { Err("conflict") };
}
let next = self.value.checked_add(amount).ok_or("overflow")?;
self.value = next;
self.receipts.insert(id, amount);
Ok("applied")
}
}
fn main() {
// Check conflict and both surviving pieces of state.
}Hint 1: the idea
Snapshot both observable fields, value and receipts, before issuing the conflicting retry. The mutant changes nothing but the stored payload.
Hint 2: a first step
Declare type Add = fn(&mut Counter, u32, u32) -> Result<&'static str, &'static str>;. In the mutant, copy the stored amount with if let Some(&previous) = counter.receipts.get(&id) so the borrow ends before you call counter.receipts.insert(id, amount).
Worked solution
use std::collections::BTreeMap;
#[derive(Default)]
struct Counter {
value: u32,
receipts: BTreeMap<u32, u32>,
}
impl Counter {
fn add(&mut self, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(previous) = self.receipts.get(&id) {
return if *previous == amount { Ok("replayed") } else { Err("conflict") };
}
let next = self.value.checked_add(amount).ok_or("overflow")?;
self.value = next;
self.receipts.insert(id, amount);
Ok("applied")
}
}
type Add = fn(&mut Counter, u32, u32) -> Result<&'static str, &'static str>;
fn conflict_overwrites(counter: &mut Counter, id: u32, amount: u32) -> Result<&'static str, &'static str> {
if let Some(&previous) = counter.receipts.get(&id) {
if previous == amount { return Ok("replayed"); }
counter.receipts.insert(id, amount);
return Err("conflict");
}
counter.add(id, amount)
}
fn conflict_test(add: Add) -> bool {
let mut counter = Counter::default();
if add(&mut counter, 7, 5) != Ok("applied") { return false; }
let old_value = counter.value;
let old_receipts = counter.receipts.clone();
add(&mut counter, 7, 8) == Err("conflict")
&& counter.value == old_value
&& counter.receipts == old_receipts
}
fn main() {
let versions: [(&str, Add); 2] = [("original", Counter::add), ("mutant", conflict_overwrites)];
for (name, add) in versions {
println!("{name}: {}", if conflict_test(add) { "pass" } else { "FAIL" });
}
}original: pass
mutant: FAILThe mutant returns the right error and leaves the value alone, so only the receipt comparison kills it. Its damage would appear later: a legitimate retry of the original amount 5 would now be rejected as a conflict, and the client that sent 8 by mistake could replay it as if it had been accepted. The next lesson moves the same discipline to output, where a failure can happen after the state has already changed.
Completion is saved in this browser only. It does not measure mastery.