Difference between hamcrest-library Matchers and hamcrest-core CoreMatchers
Asked Answered
S

3

76

It looks like the hamcrest org.hamcrest.Matchers class is very similar to org.hamcrest.CoreMatchers (though it looks like Matchers has more). Why would I choose to use CoreMatchers (other than it looks like the class is slightly smaller), and why are these two classes so similar?

Skit answered 7/6, 2012 at 13:35 Comment(0)
P
58

The Hamcrest matchers are split into several modules. The "core" includes the most basic matchers and abstract classes required for building other matchers. org.hamcrest.CoreMatchers includes the factory methods for just these matchers. The other matchers are in the "library" module grouped by the types of objects they match and are optional. org.hamcrest.Matchers includes both sets of matchers.

Which should you use? I statically import everything from the latter without any trouble. Perhaps the compile times might take slightly longer, but that's never been an issue for me. I put this at the top of my unit tests in addition to the JUnit imports:

import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;

This gives the best readability in the test methods.

Proclamation answered 8/6, 2012 at 20:45 Comment(0)
R
11

If you use Mockito a lot (as I do), you might be doing:

import org.mockito.Mockito;

or

static import org.mockito.Mockito.*;

and since the Mockito class extends Mockito's Matchers class, then you can end up with conflicts between either the Matchers classes or their static methods. Having CoreMatchers allows me to use JUnit-derived CoreMatchers in the same class as Mockito, without having to full-qualify them at their point of usage.

Raseta answered 19/3, 2013 at 22:23 Comment(0)
U
2

If you use Android's JUnit tests (not connected tests), the CoreMatchers seem to be available inside the already-included junit module, while the Matchers are not.

Thus, to save overhead, and to avoid importing another library, consider using the CoreMatcher versions of these classes if they suffice:

assertThat(chrome.twiddle(), is(equalTo(0)));

is possible using only CoreMatchers.

Unknot answered 24/6, 2018 at 13:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.