Search code examples
javamatcherassertionhamcrest

Class name has to be before method, must be MatcherAssert.assertThat() and not just assertThat()?


I'm using hamcrest matchers for a test. Why is it that I have to write

MatcherAssert.assertThat(a, Is.is(b));

and not just this?

assertThat(a, is(b));

My program errors when I try to use the latter. I really want to be able to use the latter because I need this code to be readable for someone who doesn't really know how to code.


Solution

  • Your need can be satisfied by adding

    import static org.hamcrest.MatcherAssert.assertThat;
    import static org.hamcrest.core.Is.is;
    

    to the imports section of your file. Static import was introduced to the Java language in 1.5, and you can read more here: https://docs.oracle.com/javase/1.5.0/docs/guide/language/static-import.html

    Some programming environments support automatically adding static imports for your favorite methods and classes. In Eclipse, go to Window > Preferences > Java > Editor > Content Assist > Favorites and add the MatcherAssert class there.