问题
I'm new to JUnit and Hamcrest and would like best-practice advice so I can decided which documentation to study first.
For starters, which of these assertThat methods is better?
- org.junit.Assert.assertThat (from junit-4.11.jar)
- org.hamcrest.MatcherAssert.assertThat (from hamcrest-core-1.3.jar)
According to one person last year, "JUnit has the assertThat method, but hamcrest has its own assertThat method that does the same thing.".
According to someone earlier this year, Hamcrest "could potentially give better error messages because the matcher is called to describe the mismatch".
It's hard to tell which versions of Junit and Hamcrest were compared in those posts. So I'd like a recommendation based on the most current released versions.
回答1:
It's almost the exact same thing.
Recent versions of JUnit now include hamcrest.
In fact, org.junit.Assert.assertThat 's method signature is
public static <T> void assertThat(T actual,
org.hamcrest.Matcher<T> matcher)
which you will notice uses hamcrest matchers.
You may still want to include your own version of hamcrest because JUnit isn't updated very often and may not always use the latest version of hamcrest.
According to the maven pom, JUnit 4.11 uses hamcrest 1.3 which I believe is the most current as of this writing.
EDIT
I've just read your second article http://blog.code-cop.org/2014/02/assert-or-matcherassert.html and it describes 2 slight differences in the hamcrest assertThat that make it more useful:
- when the match fails, the error message includes what was different instead of "expected X but was Y". custom hamcrest matchers may include more detailed information about what exactly was wrong by implementing
describeMismatch(). - The
assertThatsignature is different in hamcrest usingT actual, Matcher<? super T> matcherwhich allows matchers to be super types (like Matcher to compare Integers and Doubles). This usually doesn't matter but when you need it this is a nice feature to have.
So use org.hamcrest.MatcherAssert.assertThat.
回答2:
An excerpt from JUnit 5's User Guide:
However, JUnit Jupiter’s
org.junit.jupiter.Assertionsclass does not provide anassertThat()method like the one found in JUnit 4’sorg.junit.Assertclass which accepts a HamcrestMatcher. Instead, developers are encouraged to use the built-in support for matchers provided by third-party assertion libraries.
I think for JUnit 4, Hamcrest's assertThat is (officially) preferred.
来源:https://stackoverflow.com/questions/27256429/is-org-junit-assert-assertthat-better-than-org-hamcrest-matcherassert-assertthat