问题描述
我是JUnit和Hamcrest的新手,并希望获得最佳实践建议,以便我可以决定首先学习哪些文档。
I'm new to JUnit and Hamcrest and would like best-practice advice so I can decided which documentation to study first.
对于初学者来说,这些 assertThat
方法更好?
For starters, which of these assertThat
methods is better?
- org.junit.Assert.assertThat(来自junit- 4.11.jar)
- org.hamcrest.MatcherAssert.assertThat(来自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.".
根据今年早些时候的人的说法,Hamcrest 。
According to someone earlier this year, Hamcrest "could potentially give better error messages because the matcher is called to describe the mismatch".
很难说Junit和Hamcrest的哪个版本是c在这些职位上小心翼翼。所以我想要一个基于最新发布版本的推荐。
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.
推荐答案
它几乎完全相同的事情。
JUnit的最新版本现在包括hamcrest。
Recent versions of JUnit now include hamcrest.
实际上,org.junit.Assert .assert这个方法签名是
In fact, org.junit.Assert.assertThat 's method signature is
public static <T> void assertThat(T actual,
org.hamcrest.Matcher<T> matcher)
你会注意到使用hamcrest匹配器。
which you will notice uses hamcrest matchers.
你可能仍然想要包含你自己的hamcrest版本,因为JUnit不经常更新,可能并不总是使用最新版本的hamcrest。
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.
根据maven pom,
JUnit 4.11使用hamcrest 1.3,我相信这是写作时最新的。
According to the maven pom,JUnit 4.11 uses hamcrest 1.3 which I believe is the most current as of this writing.
编辑
我刚看完你的第二篇文章它描述了2个细微差别hamcrest assertThat
使其更有用:
EDITI'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:
- 当匹配失败时,错误消息包括不同的内容,而不是预期的X但是是Y。自定义hamcrest匹配器可能包含有关通过实现
describeMismatch()
确切错误的更多详细信息。 -
assertThat
签名在hamcrest中使用T actual,Matcher<?超级T> matcher
允许匹配器为超类型(比如Matcher比较整数和双精度)。这通常没关系,但是当你需要它时,这是一个很好的功能。
- 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
assertThat
signature is different in hamcrest usingT actual, Matcher<? super T> matcher
which 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.
所以请使用 org.hamcrest.MatcherAssert.assertThat
。
这篇关于org.junit.Assert.assert是否比org.hamcrest.MatcherAssert.assert更好?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!