Skip to content

What a property is

A test written by hand checks the inputs its author thought of. That’s often fine, and it’s often where a bug hides: in the input nobody thought to try. A property is a way to stop choosing the inputs yourself.

An example test says “for this input, this happens”. A property says “for every input of this kind, this holds”:

SortTest.java
@Test
void sortKeepsSize() {
forAll(lists(integers()))
.example(List.of(0, 0))
.check(xs -> assertEquals(xs.size(), sort(xs).size()));
}

It has three parts:

  • The inputs, lists(integers()): a domain, which says what kind of value to draw. Here, any list of ints.
  • The rule, in check: what must be true for each input. It’s an ordinary assertion, in the assertion library your tests already use.
  • Examples, optional, with .example(…): inputs you’ve chosen, which run first, every time. A property can say both “for every list” and “and this one in particular”.

It sits inside a plain @Test and your test framework runs it as it runs any other test. There’s no runner of proptastic’s own.

A run tries the property on many inputs, 100 unless you say, each drawn at random from the domain, with a lean toward the edges: 0, the empty list, the largest number. If every input passes, the test passes.

If one fails, proptastic doesn’t stop there. It shrinks the input to the smallest one that still fails the same way, and reports that, the counterexample, with a line to pin it as an example, so the bug can’t come back unnoticed.

The hard part is saying what must hold. Some rules come up again and again, and Patterns has the common ones: a round trip (parsing what you formatted gives it back), an invariant (a playlist never holds more than five songs), a comparison with a simpler version you trust. A bank account builds one up step by step.

A pass says the rule held for the inputs drawn, and says nothing of the rest. Drawing many inputs, and the edges on purpose, finds far more than a few hand-picked ones, but it isn’t a proof. How sure is a pass? works out what one is worth.

Privacy