Skip to content

ph unittest property

Philip Helger edited this page Nov 23, 2026 · 3 revisions

Property based testing with shrinking, independent of the test framework (since 12.8.0).

Instead of hand picked examples, a property describes what must hold for all inputs. The library generates the inputs and, if a property fails, shrinks the input to the smallest counterexample it can find. The only dependency is ph-annotations, so it can be used in the tests of every ph-commons module, including ph-base.

Highlights:

  • PropertyChecker - runs a property with 1 to 4 generated arguments from a plain JUnit 4 @Test method. A failure is reported as PropertyFailedError (an AssertionError) with the shrunk sample, the original sample and the seed to reproduce it
  • Generators - building blocks for ints, bytes, booleans, fixed values, choices, lists, byte arrays, strings (from an alphabet, a character range or arbitrary Unicode) and mutated byte arrays (valid input with random edits, to test decoders)
  • IGenerator - map, filter and flatMap to build custom generators. Shrinking works through all of them
  • PropertyAssume - discards samples that do not meet a precondition

Example:

@Test
public void testRoundTrip ()
{
  final Base64Codec aCodec = new Base64Codec ();
  new PropertyChecker ().forAll (Generators.byteArrays (),
                                 aBytes -> assertArrayEquals (aBytes, aCodec.getDecoded (aCodec.getEncoded (aBytes))));
}

How shrinking works: all random decisions of a generator are recorded as a sequence of numbers. The shrinker makes this sequence shorter and its numbers smaller and replays it through the same generator, keeping every candidate that still fails with the same exception class. As generators map smaller numbers to simpler values, this finds minimal counterexamples without any type specific code.

Configuration via system properties:

  • ph.property.tries - the number of samples per property (default 200). setTries in code takes precedence
  • ph.property.tries.factor - multiplies the number of samples of all properties, including the ones set in code with setTries. E.g. -Dph.property.tries.factor=50 for a thorough nightly run
  • ph.property.seed - the seed of all runs, to reproduce a failure. Takes precedence over setSeed in code

An invalid value of one of these system properties (no number, or a number of tries or a factor that is not positive) causes an IllegalArgumentException that names the system property.

Maven usage

Add the following to your pom.xml to use this artifact (test scope):

<dependency>
  <groupId>com.helger.commons</groupId>
  <artifactId>ph-unittest-property</artifactId>
  <version>x.y.z</version>
  <scope>test</scope>
</dependency>

Clone this wiki locally