当我查看 Assert 类 JavaDoc 中的示例时
assertThat("Help! Integers don't work", 0, is(1)); // fails:
// failure message:
// Help! Integers don't work
// expected: is <1>
// got value: <0>
assertThat("Zero is one", 0, is(not(1))) // passes
我没有看到比 assertEquals(0, 1)
有很大的优势。
如果结构变得更复杂,消息可能会很好,但您是否看到更多优势?可读性?
最佳答案
对于那些存在与您的意图完全匹配的 assertFoo
的情况没有太大的优势。在这些情况下,它们的行为几乎相同。
但是,当您遇到更复杂的检查时,优势就会变得更加明显:
val foo = List.of("someValue");
assertTrue(foo.contains("someValue") && foo.contains("anotherValue"));
Expected: is <true>
but: was <false>
对比
val foo = List.of("someValue");
assertThat(foo, containsInAnyOrder("someValue", "anotherValue"));
Expected: iterable with items ["someValue", "anotherValue"] in any order
but: no item matches: "anotherValue" in ["someValue"]
人们可以讨论其中哪一个更容易阅读,但是一旦断言失败,你会从 assertThat
得到一个很好的错误消息,但只有非常少量的信息来自 assertTrue
.
关于java - 为什么我应该使用 Hamcrest-Matcher 和 assertThat() 而不是传统的 assertXXX()-Methods,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1701113/