DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Building Scalable Real-Time Apps with AstraDB and Vaadin
Register Now

Trending

  • Micro Frontends on Monorepo With Remote State Management
  • Redefining DevOps: The Transformative Power of Containerization
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Five Java Books Beginners and Professionals Should Read

Trending

  • Micro Frontends on Monorepo With Remote State Management
  • Redefining DevOps: The Transformative Power of Containerization
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Five Java Books Beginners and Professionals Should Read
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Using Hamcrest and JUnit

Using Hamcrest and JUnit

Rafael Naufal user avatar by
Rafael Naufal
·
Apr. 05, 10 · Interview
Like (0)
Save
Tweet
Share
36.97K Views

Join the DZone community and get the full member experience.

Join For Free

Lately I started using the core Hamcrest matchers bundled with the JUnit framework to create more readable unit tests.

Hamcrest matchers were created to improve the readability of unit testing code. It’s a framework which facilitates the creation of matcher objects to match rules specified in unit tests. Some examples will let it to be clearer:

import static org.hamcrest.CoreMatchers.equalTo;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;

@Test
public void shouldBeTheSamePerson()
{
Person me = new Person( "Rafael" );
Person theOther = new Person( "Rafael" );
assertThat( me, is( theOther ) );
}

@Test
public void shouldHaveFixedSizeNumbers()
{
List<Integer> numbers = Arrays.asList( 1, 2, 3, 4, 5 );
assertThat( numbers.size(), is( equalTo( 5 ) ) );
}

The first example checks if one Person object is equal to another using the Object equals method, which was overridden in the Person class. The is syntax defines a matcher which is a shorthand to is(equalTo(value)). The second one uses the is(equalTo(value)) matcher to check the size of an integer list of fixed size numbers. The assertThat method is used in conjunction with the is(equalTo(value)) matcher, which makes the test sentence very human readable.

An interesting thing is the possibility to create a custom matcher, like this one which tests if a given list only has even numbers:

public class AreEvenNumbers extends TypeSafeMatcher<Collection<Integer>> {

@Override
public boolean matchesSafely(Collection<Integer> numbers) {
for (Integer number : numbers) {
if (number % 2 != 0) {
return false;
}
}
return true;
}

@Override
public void describeTo(Description description) {
description.appendText("even numbers");
}

@Factory
public static <T> Matcher<Collection<Integer>> evenNumbers() {
return new AreEvenNumbers();
}
}

And below are two tests which uses the AreEvenNumbers custom matcher:

import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static br.com.rafael.hamcrest.AreEvenNumbers.evenNumbers;

@Test
public void shouldHaveOnlyEvenNumbers()
{
List<Integer> numbers = Arrays.asList( 2, 4, 6, 8, 10 );
assertThat( numbers, is( evenNumbers() ) );
}

@Test
public void shouldNotHaveOddNumbers()
{
List<Integer> numbers = Arrays.asList( 1, 2, 4, 6, 8, 10 );
assertThat( numbers, not( evenNumbers() ) );
}

 These two tests use the static factory method evenNumbers to instantiate the matcher on the test code. Not the use of the not matcher on the shouldNotHaveOddNumbers test to assert that no odd numbers are present on the given list. All tests use the static import feature, which turns the test not clean and not cluttered with the class qualification.

I haven’t experienced the other common matchers on unit testing code, like the Beans, Collections and Number ones. I think they turn the tests more readable, clean and easy to change. And you? Have you ever used Hamcrest matcher? If you have other examples of using it, post them here!

 From http://rafaelnaufal.com/blog/2010/03/15/using-hamcrest-and-junit/

 

unit test Hamcrest JUnit

Opinions expressed by DZone contributors are their own.

Trending

  • Micro Frontends on Monorepo With Remote State Management
  • Redefining DevOps: The Transformative Power of Containerization
  • Cypress Tutorial: A Comprehensive Guide With Examples and Best Practices
  • Five Java Books Beginners and Professionals Should Read

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: