Is there a version of JUnit assertThat which uses the Hamcrest 'describeMismatch' functionality?
In every version of JUnit I have tried (up to 4.8.1), a failing assertThat will display an error message that looks like:
expected: [describeTo]
got: [String representation of object]In other words, it will display the toString() of the object instead of the mismatch description from the Matcher. If I use the assertThat from org.hamcrest.MatcherAssert.assertThat, then it will call 'describeMismatch' and display a more helpful error message.
Am I using Junit incorrectly or is there currently no version of JUnit that will do what I want? Do most people use the Hamcrest ass开发者_开发技巧ertThat then?
Short answer: no.
As far as I can tell, the most recent version of Hamcrest (1.2) has introduced type signatures which are incompatible with version 1.1, which JUnit currently depends on. I am not sure the extent of the damage (so to speak) created by the change in Hamcrest, but it does not appear that the JUnit team are in any hurry to upgrade (see the open issue).
I am not entirely sure I have solved my issue, but I am planning to use MatcherAssert.assertThat()
. This can require a specific release of JUnit (junit-dep-xxx I believe) which will not have classpath conflicts with Hamcrest. Otherwise you may receive NoSuchMethodErrors
when assertThat()
makes the call to describeMismatch()
.
Yes, this is fixed by this commit in JUnit 4.11:
As pointed out by Steve Freeman of Hamcrest, the Matcher interface now has an additional method describeMismatch. To be safe to catch such improvements in the future, MatcherAssert is used instead of duplicating its implementation.
Along with the upgrade to Hamcrest 1.3 (also in 4.11), these two versions work well together.
Use the other version assertThat(String, T, Matcher<T>)
and in the first argument write your own message that will give you a better description of the failure.
精彩评论