Conservation
Money moved between accounts, items moved between warehouses, a bill split between friends: the amount shouldn’t change, only where it is. A rounding or an off-by-one loses a cent or makes one, and nobody notices until the books don’t balance. Conservation totals it before and after, and checks nothing was made or lost.
The example
Section titled “The example”Friends split a restaurant bill. Each pays a share, in cents:
/** Each person's share of the bill, in cents. */static List<Long> split(long totalInCents, int people) { return Collections.nCopies(people, totalInCents / people);}However big the bill and however many people, the shares should add up to the bill:
@Testvoid splittingABillKeepsEveryCent() { forAll(longs().atLeast(0).atMost(100_000), integers().atLeast(1).atMost(12)) .check( (totalInCents, people) -> { var shares = Bill.split(totalInCents, people); long paid = shares.stream().mapToLong(Long::longValue).sum();
assertEquals(totalInCents, paid); });}When it fails
Section titled “When it fails”expected: <1> but was: <0>
splittingABillKeepsEveryCent failed after 1 try (seed 0x3a9b3a170143cbac) shrunk counterexample: totalInCents = 1, people = 2 pin it: .example(/* totalInCents */ 1L, /* people */ 2) rerun: PROPTASTIC_SEED=0x3a9b3a170143cbac ./gradlew test --tests 'ConservationTest.splittingABillKeepsEveryCent'One cent between two people is no cent each, so the cent is lost. Any bill that doesn’t divide evenly loses what’s left over, less than a cent per person. A test that splits 1,000 cents between four passes. A fix gives the leftover cents, one each, to the first few people.
The shrunk counterexample is the smallest bill and the fewest people that lose a cent. With one person nothing can be lost, so two is as small as it gets.
Reach for it when…
Section titled “Reach for it when…”- something is moved, split or regrouped, and the total should stay put: money, stock, votes, the bytes in a stream, the elements of a list;
- the code rounds, as money and percentages do;
- you can’t say what each part should be, but you know what they add up to.
It won’t catch…
Section titled “It won’t catch…”- A total that’s right with the parts wrong. Giving one person the whole bill keeps every cent. Add a property for fairness: no two shares differ by more than a cent.
- Losses that cancel out. A bug that loses a cent here and makes one there keeps the total. The bank page’s list of transfers checks the total once, at the end; check it after every step, as an invariant does, to see each step’s own mistake.
In the literature
Section titled “In the literature”The name comes from physics, where a conservation law says a quantity, such as energy, is neither made nor destroyed. In testing it’s an invariant over a sum, and the classic example is money in a bank.