我为什么要使用Hamcrest-Matcher和assertThat()而不是传统的assertXXX() - 方法 [英] Why should I use Hamcrest-Matcher and assertThat() instead of traditional assertXXX()-Methods

查看:345
本文介绍了我为什么要使用Hamcrest-Matcher和assertThat()而不是传统的assertXXX() - 方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我查看Assert类中的示例JavaDoc

When I look at the examples in the Assert class 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)

I dont see a big advantage over, let's say, assertEquals( 0, 1 ).

如果构造变得更复杂但是你看到更多优点,那么对于消息可能很好吗?可读性?

It's nice maybe for the messages if the constructs get more complicated but do you see more advantages? Readability?

推荐答案

对于 assertFoo 的情况没有大的优势与您的意图完全匹配的存在。在这些情况下,它们的行为几乎相同。

There's no big advantage for those cases where an assertFoo exists that exactly matches your intent. In those cases they behave almost the same.

但是当你进行更复杂的检查时,优势变得更加明显:

But when you come to checks that are somewhat more complex, then the advantage becomes more visible:

assertTrue(foo.contains("someValue") && foo.contains("anotherValue"));

vs。

assertThat(foo, hasItems("someValue", "anotherValue"));

可以讨论哪一个更容易阅读,但一旦断言失败,你就会从 assertThat 获取一条好的错误消息,但只有来自 assertTrue 的非常少量的信息。

One can discuss which one of those is easier to read, but once the assert fails, you'll get a good error message from assertThat, but only a very minimal amount of information from assertTrue.

assertThat 会告诉你断言是什么以及你得到了什么。 assertTrue 只会告诉您 false 您预期 true

assertThat will tell you what the assertion was and what you got instead. assertTrue will only tell you that you got false where you expected true.

这篇关于我为什么要使用Hamcrest-Matcher和assertThat()而不是传统的assertXXX() - 方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆