I’ve done a few articles about Hamcrest Matchers now, and you may or may not think they’re the bee’s knees, the way I do. But there’s another great contender out there for better, cleaner, and more fluent assertions than the defaults with JUnit: AssertJ. I will admit, AssertJ is a great framework, and it’s certainly useful.
For those of you who don’t know about AssertJ, check out their home page. One of the largest factors going for AssertJ is the chaining of assertions into one nice assertion. For example, you could do something like the following:
assertThat("string to be tested").startsWith("str").contains("to").hasLength(19);
Note: I completely made up the assertion calls in the above code. so don’t copy it, hoping that it’ll work as-is without creating your own AssertJ class. Continue Reading
Last time, I went over what a Hamcrest Matcher was, how it’s used, and how to make one. In this article, I will explain more advanced steps in the creation of Hamcrest Matchers. First, I’ll share how to make your matchers more easily type-safe, then some techniques for stateless Matchers, then finally how to cut down on so many static imports on your test classes. I’ll also give some quick tips on naming your static factory methods.
You may have noticed in the matches() method that we developed last time, I put in a comment that I had used the “yoda condition” to avoid a null check as well as a type check. First off, it wouldn’t hurt to do a little bit of research on yoda conditions yourself (I may put out an article about it someday, but no guarantees), but the biggest thing to note here is that some sort of type check and null check is needed. This is because the matches() method takes in an object, not the type specified in the generics argument. Continue Reading
Intro to Hamcrest Matchers
First things first, I should quickly explain what a Hamcrest Matcher is. When doing unit testing, the built-in assertion types that come with the testing framework are generally pretty limited. They make it very easy for a person to end up multiple asserts to essentially check one thing. Even if it doesn’t multiple asserts, those asserts aren’t the most fluent to read and don’t tell exactly what you’re checking.
That’s where Hamcrest Matchers come in (and AssertJ Matchers, but that’s for another time). They allow you to define your own more robust and more fluent assertions, essentially. For example, if you were testing whether a method correctly returns an empty String, that test might look something like this:
public void testUsingMatcher()
string = methodThatShouldReturnAnEmptyString();