Intro
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.
Typesafe Matchers
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



