Skip to content

Ledger Contract Tests

The Course
•
20 min study

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.

Predict, then run Java
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
Text
true
false

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

Compare the boundary case Java
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
Text
Normalization protected

Run the complete project

Run the ledger checks Java
public record Accepted(int inserted, int replayed) implements ImportOutcome { public Accepted { if (inserted < 0 || replayed < 0) { throw new IllegalArgumentException("negative count"); } } } public enum Category { FOOD, TRAVEL, OTHER } import java.math.BigDecimal; import java.math.RoundingMode; /** One currency; immutable, normalized values make exact replay comparison meaningful. */ public record Expense(String id, Category category, BigDecimal amount) { public Expense { if (id == null || id.trim().isEmpty()) { throw new IllegalArgumentException("id required"); } id = id.trim(); if (id.length() > 24 || id.contains(";") || id.contains("\n") || id.contains("\r")) { throw new IllegalArgumentException("invalid id"); } if (category == null || amount == null) { throw new IllegalArgumentException("category and amount required"); } if (amount.signum() <= 0 || amount.compareTo(new BigDecimal("1000000.00")) > 0) { throw new IllegalArgumentException("amount outside 0.01..1000000.00"); } try { amount = amount.setScale(2, RoundingMode.UNNECESSARY); } catch (ArithmeticException error) { throw new IllegalArgumentException("amount needs at most two decimal places", error); } } } import java.math.BigDecimal; /** Small unquoted format: id;category;amount. Categories are case-sensitive. */ public final class ExpenseParser { public Expense parse(String line) { if (line == null || line.length() > 120) { throw new IllegalArgumentException("line missing or longer than 120 characters"); } String[] fields = line.split(";", -1); if (fields.length != 3) { throw new IllegalArgumentException("expected id;category;amount"); } String decimal = fields[2].trim(); // Reject exponents and unbounded scale before BigDecimal construction. if (!decimal.matches("[0-9]{1,7}(\\.[0-9]{1,2})?")) { throw new IllegalArgumentException("amount needs digits and up to two decimal places"); } Category category; try { category = Category.valueOf(fields[1].trim()); } catch (IllegalArgumentException error) { throw new IllegalArgumentException("category must be FOOD, TRAVEL or OTHER", error); } return new Expense(fields[0], category, new BigDecimal(decimal)); } } public sealed interface ImportOutcome permits Accepted, Rejected {} import java.io.BufferedReader; import java.io.StringReader; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** Single-threaded, in-memory atomic imports; no persistence or concurrent guarantee. */ public final class Ledger { private Map<String, Expense> entries = new LinkedHashMap<>(); private final ExpenseParser parser; public Ledger(ExpenseParser parser) { if (parser == null) { throw new IllegalArgumentException("parser required"); } this.parser = parser; } public ImportOutcome importText(String text) { if (text == null || text.length() > 12000) { return new Rejected(List.of(new Problem(0, "input missing or longer than 12000 characters"))); } Map<String, Expense> candidate = new LinkedHashMap<>(entries); List<Problem> problems = new ArrayList<>(); int inserted = 0; int replayed = 0; int lineNumber = 0; try (BufferedReader reader = new BufferedReader(new StringReader(text))) { String line = reader.readLine(); while (line != null) { lineNumber++; if (lineNumber > 100) { problems.add(new Problem(lineNumber, "more than 100 physical lines")); break; } // Even whitespace-only lines must obey the per-line size limit. if (line.length() > 120) { problems.add(new Problem(lineNumber, "line longer than 120 characters")); } else if (!line.trim().isEmpty()) { try { Expense incoming = parser.parse(line); Expense old = candidate.get(incoming.id()); if (old == null) { candidate.put(incoming.id(), incoming); inserted++; } else if (old.equals(incoming)) { replayed++; } else { problems.add(new Problem(lineNumber, "conflicting id: " + incoming.id())); } } catch (IllegalArgumentException error) { problems.add(new Problem(lineNumber, error.getMessage())); } } line = reader.readLine(); } } catch (IOException error) { throw new IllegalStateException("in-memory read failed", error); } if (candidate.size() > 100) { problems.add(new Problem(0, "ledger capacity is 100 expenses")); } if (!problems.isEmpty()) { return new Rejected(problems); } // This assignment is the only commit point. entries = candidate; return new Accepted(inserted, replayed); } public Optional<Expense> find(String id) { return Optional.ofNullable(entries.get(id)); } public List<Expense> snapshot() { return List.copyOf(entries.values()); } public BigDecimal total() { return entries.values().stream() .map(Expense::amount) .reduce(new BigDecimal("0.00"), BigDecimal::add); } public List<Expense> largestFirst() { Comparator<Expense> byAmount = Comparator.comparing(Expense::amount); return entries.values().stream() .sorted(byAmount.reversed().thenComparing(Expense::id)) .toList(); } public String exportText() { List<Expense> ordered = new ArrayList<>(entries.values()); ordered.sort(Comparator.comparing(Expense::id)); StringBuilder result = new StringBuilder(); for (Expense expense : ordered) { result.append(expense.id()).append(';') .append(expense.category()).append(';') .append(expense.amount().toPlainString()).append('\n'); } return result.toString(); } } public class Main { public static void main(String[] args) { Ledger ledger = new Ledger(new ExpenseParser()); String text = "B;TRAVEL;12.50\nA;FOOD;3.25\n"; System.out.println(describe(ledger.importText(text))); System.out.println(describe(ledger.importText(text))); System.out.println(describe(ledger.importText("C;OTHER;2.00\nA;FOOD;9.00"))); System.out.println("Total: " + ledger.total().toPlainString()); System.out.print(ledger.exportText()); } static String describe(ImportOutcome outcome) { return switch (outcome) { case Accepted accepted -> "Inserted: " + accepted.inserted() + ", replayed: " + accepted.replayed(); case Rejected rejected -> "Rejected: " + rejected.problems().size() + " problem(s)"; }; } } /** Line 0 means a whole-input limit or missing-input problem. */ public record Problem(int line, String message) { public Problem { if (line < 0 || message == null || message.isEmpty()) { throw new IllegalArgumentException("valid problem required"); } } } import java.util.List; public record Rejected(List<Problem> problems) implements ImportOutcome { public Rejected { problems = List.copyOf(problems); if (problems.isEmpty()) { throw new IllegalArgumentException("rejection needs a problem"); } } } 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(); 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 check(String name, boolean condition) { if (!condition) { throw new AssertionError(name); } } }
Check your prediction
Text
All ledger checks passed

The 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

Exercise

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.

Mutation workspace Java
public record Accepted(int inserted, int replayed) implements ImportOutcome { public Accepted { if (inserted < 0 || replayed < 0) { throw new IllegalArgumentException("negative count"); } } } public enum Category { FOOD, TRAVEL, OTHER } import java.math.BigDecimal; import java.math.RoundingMode; /** One currency; immutable, normalized values make exact replay comparison meaningful. */ public record Expense(String id, Category category, BigDecimal amount) { public Expense { if (id == null || id.trim().isEmpty()) { throw new IllegalArgumentException("id required"); } id = id.trim(); if (id.length() > 24 || id.contains(";") || id.contains("\n") || id.contains("\r")) { throw new IllegalArgumentException("invalid id"); } if (category == null || amount == null) { throw new IllegalArgumentException("category and amount required"); } if (amount.signum() <= 0 || amount.compareTo(new BigDecimal("1000000.00")) > 0) { throw new IllegalArgumentException("amount outside 0.01..1000000.00"); } try { amount = amount.setScale(2, RoundingMode.UNNECESSARY); } catch (ArithmeticException error) { throw new IllegalArgumentException("amount needs at most two decimal places", error); } } } import java.math.BigDecimal; /** Small unquoted format: id;category;amount. Categories are case-sensitive. */ public final class ExpenseParser { public Expense parse(String line) { if (line == null || line.length() > 120) { throw new IllegalArgumentException("line missing or longer than 120 characters"); } String[] fields = line.split(";", -1); if (fields.length != 3) { throw new IllegalArgumentException("expected id;category;amount"); } String decimal = fields[2].trim(); // Reject exponents and unbounded scale before BigDecimal construction. if (!decimal.matches("[0-9]{1,7}(\\.[0-9]{1,2})?")) { throw new IllegalArgumentException("amount needs digits and up to two decimal places"); } Category category; try { category = Category.valueOf(fields[1].trim()); } catch (IllegalArgumentException error) { throw new IllegalArgumentException("category must be FOOD, TRAVEL or OTHER", error); } return new Expense(fields[0], category, new BigDecimal(decimal)); } } public sealed interface ImportOutcome permits Accepted, Rejected {} import java.io.BufferedReader; import java.io.StringReader; import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; import java.util.Comparator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Optional; /** Single-threaded, in-memory atomic imports; no persistence or concurrent guarantee. */ public final class Ledger { private Map<String, Expense> entries = new LinkedHashMap<>(); private final ExpenseParser parser; public Ledger(ExpenseParser parser) { if (parser == null) { throw new IllegalArgumentException("parser required"); } this.parser = parser; } public ImportOutcome importText(String text) { if (text == null || text.length() > 12000) { return new Rejected(List.of(new Problem(0, "input missing or longer than 12000 characters"))); } Map<String, Expense> candidate = new LinkedHashMap<>(entries); List<Problem> problems = new ArrayList<>(); int inserted = 0; int replayed = 0; int lineNumber = 0; try (BufferedReader reader = new BufferedReader(new StringReader(text))) { String line = reader.readLine(); while (line != null) { lineNumber++; if (lineNumber > 100) { problems.add(new Problem(lineNumber, "more than 100 physical lines")); break; } // Even whitespace-only lines must obey the per-line size limit. if (line.length() > 120) { problems.add(new Problem(lineNumber, "line longer than 120 characters")); } else if (!line.trim().isEmpty()) { try { Expense incoming = parser.parse(line); Expense old = candidate.get(incoming.id()); if (old == null) { candidate.put(incoming.id(), incoming); inserted++; } else if (old.equals(incoming)) { replayed++; } else { problems.add(new Problem(lineNumber, "conflicting id: " + incoming.id())); } } catch (IllegalArgumentException error) { problems.add(new Problem(lineNumber, error.getMessage())); } } line = reader.readLine(); } } catch (IOException error) { throw new IllegalStateException("in-memory read failed", error); } if (candidate.size() > 100) { problems.add(new Problem(0, "ledger capacity is 100 expenses")); } if (!problems.isEmpty()) { return new Rejected(problems); } // This assignment is the only commit point. entries = candidate; return new Accepted(inserted, replayed); } public Optional<Expense> find(String id) { return Optional.ofNullable(entries.get(id)); } public List<Expense> snapshot() { return List.copyOf(entries.values()); } public BigDecimal total() { return entries.values().stream() .map(Expense::amount) .reduce(new BigDecimal("0.00"), BigDecimal::add); } public List<Expense> largestFirst() { Comparator<Expense> byAmount = Comparator.comparing(Expense::amount); return entries.values().stream() .sorted(byAmount.reversed().thenComparing(Expense::id)) .toList(); } public String exportText() { List<Expense> ordered = new ArrayList<>(entries.values()); ordered.sort(Comparator.comparing(Expense::id)); StringBuilder result = new StringBuilder(); for (Expense expense : ordered) { result.append(expense.id()).append(';') .append(expense.category()).append(';') .append(expense.amount().toPlainString()).append('\n'); } return result.toString(); } } public class Main { public static void main(String[] args) { Ledger ledger = new Ledger(new ExpenseParser()); String text = "B;TRAVEL;12.50\nA;FOOD;3.25\n"; System.out.println(describe(ledger.importText(text))); System.out.println(describe(ledger.importText(text))); System.out.println(describe(ledger.importText("C;OTHER;2.00\nA;FOOD;9.00"))); System.out.println("Total: " + ledger.total().toPlainString()); System.out.print(ledger.exportText()); } static String describe(ImportOutcome outcome) { return switch (outcome) { case Accepted accepted -> "Inserted: " + accepted.inserted() + ", replayed: " + accepted.replayed(); case Rejected rejected -> "Rejected: " + rejected.problems().size() + " problem(s)"; }; } } /** Line 0 means a whole-input limit or missing-input problem. */ public record Problem(int line, String message) { public Problem { if (line < 0 || message == null || message.isEmpty()) { throw new IllegalArgumentException("valid problem required"); } } } import java.util.List; public record Rejected(List<Problem> problems) implements ImportOutcome { public Rejected { problems = List.copyOf(problems); if (problems.isEmpty()) { throw new IllegalArgumentException("rejection needs a problem"); } } } 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(); 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 check(String name, boolean condition) { if (!condition) { throw new AssertionError(name); } } }
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:

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

Text
All ledger checks passed

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

Was this article helpful?

Your response is saved on this device.