Category Archives: Blog

What if AssertJ used Java 8

If you write tests for your java code, there’s a chance you use Fest-Assert or AssertJ.

If you don’t know AssertJ, go test it.

Getting addicted is as easy as writing a first test with it. Here’s a sample test you might write today, just after you close this blog post:

import static org.assertj.core.api.Assertions.*;
import java.util.*;
import org.junit.*;

public class CollectionsSort {
  @Test
  public void sort() {
    List cities = Arrays.asList("Paris", "Berlin", "Rome");
    Collections.sort(cities);

    assertThat(cities).containsExactly("Berlin", "Paris", "Rome");
  }
}

org.assertj.core.api.Assertions implements the typical garbage class pattern. It contains a lot of static assertThat methods that we don’t know where to put otherwise.

Let’s see if Java 8 can improve the way we write tests.

With Java 8, Assertions could be an interface. With static methods only. And I would write:

  import java.util.*;
  import org.assertj.core.api.Assertions.*;
  import org.junit.*;

  public class CollectionsSort implements Assertions {
    @Test
    public void sort() {
      List cities = Arrays.asList("Paris", "Berlin", "Rome");
      Collections.sort(cities);

      assertThat(cities).containsExactly("Berlin", "Paris", "Rome");
    }
  }

Where’s the difference? Instead of using a static import, the test case inherits some assertions methods. No fields. Only static methods. This way, developers won’t forget to replace Assertions.assertThat(...) with replace assertThat(...).

Not convinced? Look at this test:

@Test
public void names() {
  List cities = Arrays.asList(new City("Paris"), new City("London"));

  assertThat(cities).extracting("name").containsExactly("Paris", "London");
}

It could leverage Java 8 method references like this:

@Test
public void names() {
  List cities = Arrays.asList(new City("Paris"), new City("London"));

  assertThat(cities).extracting(City::getName).containsExactly("Paris", "London");
}

This last example could be implemented right now in AssertJ. It would use inner classes in Java 7 and lambdas in Java 8.
The first example is trickier. It cannot be compatible with anything else than Java 8.

Anyway, expect librairies to embrace Java 8 patterns in the future.