About Dustin Marx

JUnit’s Built-in Hamcrest Core Matcher Support

In the post Improving On assertEquals with JUnit and Hamcrest, I briefly discussed Hamcrest “core” matchers being “baked in” with modern versions of JUnit. In that post, I focused particularly on use of JUnit’s assertThat(T, Matcher) static method coupled with the Hamcrest core is() matcher that is automatically included in later versions of JUnit. In this post, I look at additional Hamcrest “core” matchers that are bundled with recent versions of JUnit.

Two of the advantages of JUnit including Hamcrest “core” matchers out-of-the-box is that there is no need to specifically download Hamcrest and there is no need to include it explicitly on the unit test classpaths. Before looking at more of the handy Hamcrest “core” matchers, it is important to point out here that I am intentionally and repeatedly referring to “core” Hamcrest matchers because recent versions of JUnit only provide “core” (and not all) Hamcrest matchers automatically. Any Hamcrest matchers outside of the core matchers would still need to be downloaded separately and specified explicitly on the unit test classpath. One way to get an idea of what is Hamcrest “core” (and thus what matchers are available by default in recent versions of JUnit) is to look at that package’s Javadoc-based API documentation:

From this JUnit-provided documentation for the org.hamcrest.core package, we see that the following matchers (with their descriptions) are available:

Class

Javadoc Class Description

Covered Here?

AllOf<T>

Calculates the logical conjunction of two matchers.

Yes

AnyOf<T>

Calculates the logical disjunction of two matchers.

Yes

DescribedAs<T>

Provides a custom description to another matcher.

Yes

Is<T>

Decorates another Matcher, retaining the behavior but allowing tests to be slightly more expressive.

Is the value equal to another value, as tested by the Object.equals(java.lang.Object) invokedMethod?

Yes

IsInstanceOf

Tests whether the value is an instance of a class.

Yes

IsNot<T>

Calculates the logical negation of a matcher.

Yes

IsNull<T>

Is the value null?

Yes

IsSame<T>

Is the value the same object as another value?

Yes

In my previous post demonstrating the Hamcrest is() matcher used in conjunction with JUnit’s assertThat(), I used an IntegerArithmetic implementation as test fodder. I’ll use that again here for demonstrating some of the other Hamcrest core matchers. For convenience, that class is reproduced below.

In the Improving On assertEquals with JUnit and Hamcrest post, I relied largely on is() to compare expected results to actual results for the integer multiplication being tested. Another option would have been to use the equalTo matcher as shown in the next code listing.

Although not necessary, some developers like to use is and equalTo together because it feels more fluent to them. This is the very reason for is‘s existence: to make use of other matchers more fluent. I often use is() by itself (implying equalTo()) as discussed in Improving On assertEquals with JUnit and Hamcrest. The next example demonstrates using is() matcher in conjunction with the equalTo matcher.

The equalTo Hamcrest matcher performs a comparison similar to calling Object.equals(Object). Indeed, its comparison functionality relies on use of the underlying object’s equals(Object) implementation. This means that the last two examples will pass because the numbers being compared are logically equivalent. When one wants to ensure an even greater identity equality (actually the same objects and not just the same logical content), one can use the Hamcrest sameInstance matcher as shown in the next code listing. The not matcher is also applied because the assertion will be true and the test will pass only with the “not” in place because the expected and actual results happen to NOT be the same instances!

It is sometimes desirable to control the text that is output from an assertion of a failed unit test. JUnit includes the core Hamcrest matcher asDescribed() to support this. A code example of this is shown in the next listing and the output of that failed test (and corresponding assertion) is shown in the screen snapshot of the NetBeans IDE that follows the code listing.

The contrived class whose code was just shown provides opportunities to use additional Hamcrest “core” matchers. As described above, it’s possible to use all of these matches with the is matcher to improve fluency of the statement. Two useful “core” matchers are nullValue() and notNullValue(), both of which are demonstrated in the next JUnit-based code listing (and is is used in conjunction in one case).

Many of the Hamcrest core matchers covered so far increase fluency and readability, but I like the next two for even more reasons. The Hamcrest hasItem() matcher checks for the existence of the prescribed item in the collection and the even more useful Hamcrest hasItems() matcher checks for the existence of multiple prescribed items in the collection. It is easier to see this in code and the following code demonstrates these in action.

It is sometimes desirable to test the result of a certain tested method to ensure that it meets a wide variety of expectations. This is where the Hamcrest allOf matcher comes in handy. This matcher ensures that all conditions (expressed themselves as matchers) are true. This is illustrated in the following code listing, which tests with a single assert that a generated Set is not null, has two specific Strings in it, and is an instance of TreeSet.

Now I need to test that the sole method in the class above returns a valid integer representing a day of the week correctly. I’d like my test(s) to ensure that a valid integer representing a day Sunday through Saturday is returned, but the method being tested is such that it may not be the same day of the week returned on any given test run. The code listing below indicates how this can be tested with the JUnit-included Hamcrest “anyOf” matcher.

While Hamcrest’s allOf requires all conditions to match for the assertion to be avoided, the existence of any one condition is sufficient to ensure that anyOf doesn’t lead to an assertion of a failure.

My favorite way of determining which core Hamcrest matchers are available with JUnit is to use import completion in my Java IDE. When I statically import the org.hamcrest.CoreMatchers.* package contents, all of the available matchers are displayed. I can look in the IDE to see what the * represents to see what matchers are available to me.

It is nice to have Hamcrest “core” matchers included with JUnit and this post has attempted to demonstrate the majority of these. Hamcrest offers many useful matchers outside of the “core” that are useful as well. More details on these are available in the Hamcrest Tutorial.

Newsletter

Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

Email address:

Recent Jobs

No job listings found.

Join Us

With 1,240,600 monthly unique visitors and over 500 authors we are placed among the top Java related sites around. Constantly being on the lookout for partners; we encourage you to join us. So If you have a blog with unique and interesting content then you should check out our JCG partners program. You can also be a guest writer for Java Code Geeks and hone your writing skills!

Disclaimer

All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners. Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries. Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.