Hamcrest

Hamcrest adds a lot of methods called matchers. Each matcher is designed to perform a comparison operation. It is extensible enough to support custom matchers created by yourself. Furthermore, JUnit supports Hamcrest natively since its core is included in the JUnit distribution. You can start using Hamcrest effortlessly. However, we want to use the full-featured project so we will add a test dependency to Gradle's file:

testCompile 'org.hamcrest:hamcrest-all:1.3' 

Let us compare one assert from JUnit with the equivalent one from Hamcrest:

  • The JUnit assert:
List<String> friendsOfJoe = 
Arrays.asList("Audrey", "Peter", "Michael", "Britney", "Paul");
Assert.assertTrue( friendships.getFriendsList("Joe")
.containsAll(friendsOfJoe));
  • The Hamcrest assert:
assertThat( 
  friendships.getFriendsList("Joe"), 
  containsInAnyOrder("Audrey", "Peter", "Michael", "Britney", "Paul") 
); 

As you can see, Hamcrest is a bit more expressive. It has a much bigger range of asserts that allows us to avoid some boilerplate code and, at the same time, makes code easier to read and is more expressive.

Here's another example:

  • JUnit assert:
Assert.assertEquals(5, friendships.getFriendsList("Joe").size()); 
  • Hamcrest assert:
assertThat(friendships.getFriendsList("Joe"), hasSize(5)); 

You'll notice two differences. The first is that, unlike JUnit, Hamcrest works almost always with direct objects. While in the case of JUnit, we needed to get the integer size and compare it with the expected number (5); Hamcrest has a bigger range of asserts so we can simply use one of them (hasSize) together with the actual object (List). Another difference is that Hamcrest has the inverse order with the actual value being the first argument (like TestNG).

Those two examples are not enough to show the full potential offered by Hamcrest. Later on in this book, there will be more examples and explanations of Hamcrest. Visit http://hamcrest.org/ and explore its syntax.

The complete source code can be found in the FriendshipsHamcrestTest class in the https://bitbucket.org/vfarcic/tdd-java-ch02-example-junit repositories.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.25.41