The capstone's test entry checks public behavior across classes. Some tests focus on parsing, while others follow an import through staging, storage and reporting. Read the named checks as an executable list of promises, then challenge them with deliberate mutations.
Understand the contract
The most important rollback case has a valid new row followed by a conflicting existing ID. If a test only submits an immediately invalid first row, a partially mutating implementation could pass. The test takes a canonical export before the request and compares it afterward, and separately confirms the new ID is absent.
Replay tests distinguish identical content, normalized equivalent content and conflicting content. Report tests distinguish primary amount ordering from the ID tie-breaker. Snapshot tests attempt an edit and then make a later successful import to verify both unmodifiability and independence over time.
The test runner uses explicit AssertionError and ordinary static methods. It needs no framework or -ea option. Every test method must be called from main; defining a method does not automatically run it. Avoid catches around the whole suite, because a failure should stop execution before the final success message.
Before running, write the output you expect and explain which rule produces each line. Each editor is an independent program.
import java.util.List;
import java.util.Map;
import java.util.LinkedHashMap;
public class Main {
public static void main(String[] args) {
Map<String, Integer> current = new LinkedHashMap<>();
current.put("A", 2);
Map<String, Integer> before = new LinkedHashMap<>(current);
Map<String, Integer> candidate = new LinkedHashMap<>(current);
boolean conflict = false;
for (String id : List.of("B", "A")) {
if (candidate.containsKey(id)) {
conflict = true;
break;
}
candidate.put(id, 3);
}
if (!conflict) {
current = candidate;
}
System.out.println(current.equals(before));
System.out.println(current.containsKey("B"));
}
}Check your prediction
true
falseTrace a different case
Representation matters to generated record equality. The parser must normalize amount scale before retry comparison. This small check gives an independent expected result for normalization; a round-trip check alone might let a parser and exporter share the same defect. The project also checks malformed amount syntax before constructing the decimal. setScale(2) without a rounding mode throws for a third decimal place, as Day 2 showed, so it never rounds an amount silently.
import java.math.BigDecimal;
public class Main {
public static void main(String[] args) {
BigDecimal first = new BigDecimal("2.0").setScale(2);
BigDecimal second = new BigDecimal("2.00").setScale(2);
if (!first.equals(second)) {
throw new AssertionError("normalized replay representation");
}
System.out.println("Normalization protected");
}
}Check your prediction
Normalization protectedRun the complete project
Check your prediction
All ledger checks passedThe marked entry is LedgerTest.java. Every source tab belongs to this workspace, but only that entry's main method starts execution. Each editor has its own independent source set. To test an edit, make it in the workspace whose entry is LedgerTest.java; edits in the application editor do not carry over automatically. Download expense-ledger.zip to keep both entries and your changes together locally.
Kill a surviving mutant
Ledger Contract Tests: kill a surviving mutant
The suite above looks thorough, yet one plausible mutant survives it. In the
workspace below, open Ledger.java and change the per-line limit check from
line.length() > 120 to line.length() >= 120. Predict what LedgerTest
prints, then run it.
It still prints All ledger checks passed, although lines of exactly 120
characters are now rejected, which breaks the documented limit. Write a
testLineBoundary() method in LedgerTest.java, call it from main, and run it
against the mutant: it must fail with a named AssertionError. Then restore >
and confirm the whole suite passes again.
Hint 1: the idea
Read testLimits: it checks a 121-character line, which both versions reject. The real rule and the mutant disagree on exactly one length. A test must use that length, and check that it is accepted.
Hint 2: a first step
Build a valid row padded with trailing spaces to exactly 120 characters, for
example by appending " ".repeat(...) to "A;FOOD;1". Check its length first,
so the test cannot pass for the wrong reason, then check the import result.
Show one solution
LedgerTest.java with the new test, called last from main:
import java.math.BigDecimal;
import java.util.List;
import java.util.Random;
/** Named behavioral checks; run this entry after editing any project source. */
public class LedgerTest {
public static void main(String[] args) {
testParser();
testAtomicityAndReplay();
testReportsAndOwnership();
testLimits();
testRoundTrip();
testCapacity();
testLineBoundary();
System.out.println("All ledger checks passed");
}
static Ledger fresh() {
return new Ledger(new ExpenseParser());
}
static void testParser() {
ExpenseParser parser = new ExpenseParser();
Expense expense = parser.parse(" A ; FOOD ; 2.0 ");
check("normalized value", expense.equals(new Expense("A", Category.FOOD, new BigDecimal("2.00"))));
check("maximum amount", parser.parse("MAX;OTHER;1000000.00").amount().compareTo(new BigDecimal("1000000")) == 0);
for (String invalid : new String[] {
"A;FOOD;0", "A;FOOD;-1", "A;FOOD;1.001", "A;FOOD;1e3",
"A;FOOD;1000000.01", "A;food;1", "A;FOOD;", ";FOOD;1", "A;FOOD;1;extra", null
}) {
try {
parser.parse(invalid);
throw new AssertionError("parser accepted " + invalid);
} catch (IllegalArgumentException expected) {
// Only documented input rejection counts.
}
}
}
static void testAtomicityAndReplay() {
Ledger ledger = fresh();
check("first insertion", ledger.importText("A;FOOD;2.00").equals(new Accepted(1, 0)));
check("normalized replay", ledger.importText(" A ; FOOD ; 2.0 ").equals(new Accepted(0, 1)));
String before = ledger.exportText();
ImportOutcome conflict = ledger.importText("B;OTHER;3.00\nA;FOOD;9.00");
check("conflict rejects", conflict instanceof Rejected);
check("late conflict rollback", ledger.exportText().equals(before));
check("no partial B", ledger.find("B").isEmpty());
check("late malformed rollback", ledger.importText("C;OTHER;1.00\nbad") instanceof Rejected);
check("malformed preserved state", ledger.exportText().equals(before));
check("within batch replay", ledger.importText("D;OTHER;1.00\nD;OTHER;1.00").equals(new Accepted(1, 1)));
before = ledger.exportText();
check("within batch conflict", ledger.importText("E;OTHER;1.00\nE;OTHER;2.00") instanceof Rejected);
check("within batch rollback", ledger.exportText().equals(before));
ImportOutcome error = ledger.importText("\nbad");
if (error instanceof Rejected rejected) {
check("physical line", rejected.problems().get(0).line() == 2);
try {
rejected.problems().clear();
throw new AssertionError("mutable problems");
} catch (UnsupportedOperationException expected) {
// Error results are snapshots too.
}
} else {
throw new AssertionError("bad line accepted");
}
}
static void testReportsAndOwnership() {
Ledger ledger = fresh();
ledger.importText("B;FOOD;2.00\nA;OTHER;2.00\nC;TRAVEL;1.00");
check("exact total", ledger.total().equals(new BigDecimal("5.00")));
check("amount order", ledger.largestFirst().get(2).id().equals("C"));
check("id tie breaker", ledger.largestFirst().get(0).id().equals("A"));
check("canonical export", ledger.exportText().equals("A;OTHER;2.00\nB;FOOD;2.00\nC;TRAVEL;1.00\n"));
List<Expense> before = ledger.snapshot();
try {
before.clear();
throw new AssertionError("mutable snapshot");
} catch (UnsupportedOperationException expected) {
check("store retained", ledger.snapshot().size() == 3);
}
ledger.importText("D;OTHER;0.01");
check("old snapshot stable", before.size() == 3);
check("new snapshot updated", ledger.snapshot().size() == 4);
check("missing lookup", ledger.find("missing").isEmpty());
}
static void testLimits() {
Ledger ledger = fresh();
check("empty accepted", ledger.importText("").equals(new Accepted(0, 0)));
check("blank accepted", ledger.importText(" \n").equals(new Accepted(0, 0)));
check("empty total", ledger.total().equals(new BigDecimal("0.00")));
check("null rejected", ledger.importText(null) instanceof Rejected);
check("total character limit", ledger.importText(" ".repeat(12001)) instanceof Rejected);
check("line limit", ledger.importText(" ".repeat(121)) instanceof Rejected);
check("100 physical lines", ledger.importText("\n".repeat(100)) instanceof Accepted);
check("101 physical lines", ledger.importText("\n".repeat(101)) instanceof Rejected);
check("limits unchanged", ledger.snapshot().isEmpty());
}
static void testRoundTrip() {
Ledger original = fresh();
Random random = new Random(29);
for (int index = 0; index < 20; index++) {
int amount = random.nextInt(100) + 1;
check("generated insertion " + index, original.importText("X" + index + ";OTHER;" + amount) instanceof Accepted);
}
Ledger restored = fresh();
check("export accepted", restored.importText(original.exportText()) instanceof Accepted);
check("round trip", restored.exportText().equals(original.exportText()));
check("total round trip", restored.total().equals(original.total()));
}
static void testCapacity() {
Ledger ledger = fresh();
for (int index = 0; index < 100; index++) {
check("capacity insertion", ledger.importText("C" + index + ";OTHER;1") instanceof Accepted);
}
String before = ledger.exportText();
check("capacity rejection", ledger.importText("EXTRA;OTHER;1") instanceof Rejected);
check("capacity unchanged", ledger.exportText().equals(before));
check("replay at capacity", ledger.importText("C0;OTHER;1").equals(new Accepted(0, 1)));
Ledger restored = fresh();
check("full export accepted", restored.importText(before) instanceof Accepted);
check("full round trip", restored.exportText().equals(before));
}
static void testLineBoundary() {
Ledger ledger = fresh();
String exact = "A;FOOD;1" + " ".repeat(112);
check("line of exactly 120 characters", exact.length() == 120);
check("120-character line accepted", ledger.importText(exact).equals(new Accepted(1, 0)));
check("121-character line rejected", fresh().importText(exact + " ") instanceof Rejected);
}
static void check(String name, boolean condition) {
if (!condition) {
throw new AssertionError(name);
}
}
}Expected output with the real > check:
All ledger checks passedAgainst the >= mutant, the run stops with AssertionError: 120-character line accepted. The existing 121-character check could never tell the two apart,
because both reject it; only the exact limit can. The first check, on the
string's own length, guards the test itself: if the padding were miscounted, a
119-character line would pass under both versions and the mutant would survive
again. Asserting new Accepted(1, 0) rather than just "not rejected" also
proves the padded row was parsed as a real expense.
Change it and test again
In the mutation workspace, try one more surviving candidate: change the
12000-character input limit to >= 12000, and write the test that kills it.
Then try one mutation at a time: alias candidate to entries; treat every existing ID as a replay; remove the ID tie-breaker; or remove Expense's scale normalization. Each must fail a named behavioral assertion. Restore the original implementation and confirm the full suite passes between mutations.
Explain before moving on
Which checks prove rollback, ownership, normalization and report order? Which limits are tested exactly at and above their boundary? Passing these deterministic tests does not establish crash recovery, concurrency safety or a real financial policy.
Completion is saved in this browser only. It does not measure mastery.