How to Make Your Own Hamcrest Matchers in Kotlin

A Match made in Hamcrest-heaven!

Intro to Hamcrest Matchers

First things first, I should quickly explain what a Hamcrest Matcher is. When conducting unit tests, 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 with multiple asserts to essentially check one thing. Even if it doesn't contain multiple asserts, those asserts aren't the most fluent to read and don't tell exactly what you're checking.

You may also like: Hamcrest Containing Matchers

That's where Hamcrest Matchers come in (and other assertion libraries, but we're looking at Hamcrest right now). 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: