This is a mobile version, full one is here.

Yegor Bugayenko
17 May 2017

Single Statement Unit Tests

Many articles and books have already been written about unit testing patterns and anti-patterns. I want to add one more recommendation which, I believe, can help us make our tests, and our production code, more object-oriented. Here it is: a test method must contain nothing but a single assert.

Look at this test method from RandomStreamTest from OpenJDK 8, created by Brian Goetz:

@Test
public void testIntStream() {
  final long seed = System.currentTimeMillis();
  final Random r1 = new Random(seed);
  final int[] a = new int[SIZE];
  for (int i=0; i < SIZE; i++) {
    a[i] = r1.nextInt();
  }
  final Random r2 = new Random(seed);
  final int[] b = r2.ints().limit(SIZE).toArray();
  assertEquals(a, b);
}

There are two parts in this method: the algorithm and the assertion. The algorithm prepares two arrays of integers and the assertion compares them and throws AssertionError if they are not equal.

I'm saying that the first part, the algorithm, is the one we should try to avoid. The only thing we must have is the assertion. Here is how I would re-design this test method:

@Test
public void testIntStream() {
  final long seed = System.currentTimeMillis();
  assertEquals(
    new ArrayFromRandom(
      new Random(seed)
    ).toArray(SIZE),
    new Random(seed).ints().limit(SIZE).toArray()
  );
}
private static class ArrayFromRandom {
  private final Random random;
  ArrayFromRandom(Random r) {
    this.random = r;
  }
  int[] toArray(int s) {
    final int[] a = new int[s];
    for (int i=0; i < s; i++) {
      a[i] = this.random.nextInt();
    }
    return a;
  }
}

If Java had monikers this code would look even more elegant:

@Test
public void testIntStream() {
  assertEquals(
    new ArrayFromRandom(
      new Random(System.currentTimeMillis() as seed)
    ).toArray(SIZE),
    new Random(seed).ints().limit(SIZE).toArray()
  );
}

As you can see, there is only one "statement" in this method: assertEquals().

Hamcrest with its assertThat() and its collection of basic matchers is a perfect instrument to make our single-statement test methods even more cohesive and readable.

There are a number of practical benefits of this principle, if we agree to follow it:

The biggest benefit we get when this principle is applied to our tests is that they become declarative and object-oriented, instead of being algorithmic, imperative, and procedural.