I talked about the benifit of readable unit tests and what frameworks there are for java developers to archive good unit tests.
One of the main elements of unit tests are assertions. In JUnit we have the static methods
assertNotNull and so on. But these aren’t making a good job when it comes to easy readable code. A better readable way is to use the
assertThat method that comes with Hamcrest and is also part of the latest JUnit versions.
The problem with Hamcrest is that it is created out of many static methods which has several drawbacks. The biggest one is the bad IDE support.
In the talk I showed the framework AssertJ which is an alternative to hamcrest.
It also uses a static
assertThat method as the entry point to an assertion but the rest of the API is implemented as a fluent-API. This way the IDE is able to give suggestions of possible assertion methods based on the type that was given as argument to the
assertThat method. Look at the following example:
String message = "hello world, manuel"; assertThat(message).isNotEmpty().startsWith("hello").endsWith("manuel");
With this example the IDE knows that ‘message’ is of type String and it can only suggest assertions that are making sense for strings like
endsWith. For a parameter of type integer the IDE would instead suggest assertions like
isBetween(int start, int end).
I realy love this style of writing unit tests. In the talk I gave some other interesting examples of what AssertJ can do for you.