Skip to content

Round trip

You write data out and read it back: to text, to JSON, to a database row, over the wire. The writer and the reader are two pieces of code that have to agree, and a test that writes one value checks only that one. A round trip checks that reading undoes writing for every value.

An app shows amounts of money as people write them, 12.34 for 1,234 cents, and reads them back the same way:

Money.java
static String format(int cents) {
return cents / 100 + "." + cents % 100;
}
static int parse(String text) {
return new BigDecimal(text).movePointRight(2).intValueExact();
}

Whatever amount you start with, formatting it and parsing the text should give it back:

RoundTripTest.java
@Test
void parsingUndoesFormatting() {
forAll(integers().atLeast(0).atMost(1_000_000))
.check(cents -> assertEquals(cents, Money.parse(Money.format(cents))));
}
Terminal window
expected: <1> but was: <10>
parsingUndoesFormatting failed after 1 try (seed 0x401df1df36156c13)
shrunk counterexample: cents = 1
pin it: .example(1)
rerun: PROPTASTIC_SEED=0x401df1df36156c13 ./gradlew test --tests 'RoundTripTest.parsingUndoesFormatting'

One cent formats as 0.1, with no zero before the 1, and 0.1 is ten cents. Any amount that ends in 1 to 9 cents comes back wrong: 12.05 formats as 12.5, which reads back as 12.50. A test of 12.34 passes, because 34 has two digits. Paste the pin it: line after forAll(…) and one cent runs first, every time.

  • you have a pair of functions where one undoes the other: encode and decode, serialize and deserialize, format and parse, compress and decompress, save and load;
  • you change a format, and want to know every value still survives it;
  • you can’t say what the encoded form should be, but you know it must decode to the original.
  • A format that’s wrong both ways. If format writes 12.34 as "twelve" and parse reads "twelve" as 1,234, the round trip holds and nobody else can read it. Pin a few encoded forms with an example-based test too.
  • Values your domain doesn’t draw. Negative amounts never come up here, so a bug in formatting -0.05 can’t show. Widen the domain to what the code really takes.
  • The other direction. Text that a person typed, such as "12.5", isn’t what format writes, so parsing it then formatting it needn’t give it back. That’s a property of its own, and a weaker one.

It’s also called an inverse property, since decoding is the inverse of encoding. One of the first properties in the paper that started property-based testing is a round trip: reversing a list twice gives it back. See Claessen and Hughes, 2000 in further reading.

Privacy