Book Image

Test-Driven Java Development

Book Image

Test-Driven Java Development

Overview of this book

Table of Contents (17 chapters)
Test-Driven Java Development
About the Authors
About the Reviewers
Refactoring Legacy Code – Making it Young Again

Hamcrest and AssertJ

In the previous section, we gave an overview of what a unit test is and how it can be written using two of the most commonly used Java frameworks. Since tests are an important part of our projects, why not improve the way we write them? Some cool projects emerged, aiming to empower the semantic of tests by changing the way assertions are made. As a result, tests are more concise and easier to understand.


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: