View on GitHub


Property-Based Testing in Java

The main purpose of jqwik is to bring Property-Based Testing (PBT) to the JVM. Property-Based Testing tries to combine the intuitiveness of Microtests with the effectiveness of randomized, generated test data. Originally driven by the common hype about functional programming, PBT has meanwhile been recognized as an important ingredient of any up-to-date testing approach.


A property is supposed to describe a generic invariant or post condition of your code, given some precondition. The testing library - jqwik - will then try to generate many value sets that fulfill the precondition hoping that one of the generated sets can falsify a wrong assumption.

The following property deals with a partial implementation for the (in)famous Fizz Buzz Kata:

import java.util.*;

import net.jqwik.api.*;

class FizzBuzzTests {
	boolean every_third_element_starts_with_Fizz(@ForAll("divisibleBy3") int i) {
		return fizzBuzz().get(i - 1).startsWith("Fizz");

	Arbitrary<Integer> divisibleBy3() {
		return Arbitraries.integers(1, 100).filter(i -> i % 3 == 0);

	private List<String> fizzBuzz() {
		return IntStream.range(1, 100).mapToObj((int i) -> {
			boolean divBy3 = i % 3 == 0;
			boolean divBy5 = i % 5 == 0;

			return divBy3 && divBy5 ? "FizzBuzz"
				: divBy3 ? "Fizz"
				: divBy5 ? "Buzz"
				: String.valueOf(i);

By using a few Java annotations jqwik tries to make it as simple as possible for programmers to create Properties. Classes are used as containers to group properties that belong together.


Unlike Properties an example-based test checks the correct behaviour for a single usage scenario. Thus, examples are just a fancy name for the usual unit tests that directly specify the data being used to drive and assert a piece of code.

import static org.assertj.core.api.Assertions.*;

import net.jqwik.api.*;

class SimpleExampleTests implements AutoCloseable {
	void succeeding() { 
		assertThat(Math.sqrt(15)).isCloseTo(3.872, Offset.offset(0.01));

	void failing() {

	// Executed after each test case
	public void close() { }

	class AGroupOfCoherentTests {
		void anotherSuccess() { }

This looks like standard JUnit tests and works basically the same but without the complicated lifecycle of Before’s and After’s.