Is there a version of JUnit assertThat which uses the Hamcrest 'describeMismatch' functionality?

蹲街弑〆低调 提交于 2020-01-13 09:37:05

问题


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 assertThat then?


回答1:


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().




回答2:


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.




回答3:


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.



来源:https://stackoverflow.com/questions/3915635/is-there-a-version-of-junit-assertthat-which-uses-the-hamcrest-describemismatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!