Awaitility is a library for Java (with extensions for Groovy and Scala) to test asynchonous systems. The 1.6.0 release introduces support for AssertJ assertions as well as better Java 8 support.
Java 8
Let’s say you have a repository for storing User entities called userRepo
. You publish a command to your system that gets handled asynchronously and as an outcome a new user is persisted. To test this with Awaitility and lambdas you can do like this:
@Test public void
new_user_is_persisted_to_user_repository() {
commandPublisher.publish(new CreateUserCommand("John Doe"));
await().until( () -> userRepo.size(), is(1) );
}
Where the is
method is a standard Hamcrest matcher. The example can be simplified using method references:
@Test public void
new_user_is_persisted_to_user_repository() {
commandPublisher.publish(new CreateUserCommand("John Doe"));
await().until( userRepo::size, is(1) );
}
If the UserRepository has a method that returns a boolean
if the user repository is not empty then the test can be made even simpler:
@Test public void
new_user_is_persisted_to_user_repository() {
commandPublisher.publish(new CreateUserCommand("John Doe"));
await().until( userRepo::isNotEmpty );
}
As you can see a lot of boiler-plate code can be removed when using lambda expressions and method references instead of anonymous inner classes.
AssertJ
New in the 1.6.0 release is also support for assertion libraries other than Hamcerst. One of these libraries are AssertJ but Fest Assert or standard JUnit assertions will work as well. To do this you can supply a Runnable to the until
method in Awaitility that does the job of asserting. Since Runnable
is a functional interface in Java 8 it becomes quite nice to use:
@Test public void
new_user_is_persisted_to_user_repository() {
commandPublisher.publish(new CreateUserCommand("John Doe"));
await().until( () -> assertThat(userRepo.size()).isEqualTo(1) );
}
assertThat
in this example is statically imported from the AssertJ library.
The examples aren’t in the HTML at all.
Something probably went wrong when Jayway updated to a new version of WordPress or moved it to another server. I’ve fixed it now, thanks for pointing out.