[英]How to know what causes an assertEquals method to fail in unit tests?
I am missing good failure messages when using assertEquals() on objects or collections. 在对象或集合上使用assertEquals()时,我缺少良好的失败消息 。 When it fails, the error message prints out the expected object and the actual object using toString() method.
当失败时,错误消息将使用toString()方法打印出预期的对象和实际的对象。 It does not print out exactly what causes the inequality.
它不能完全打印出导致不平等的原因。 Certainly when comparing two collections, the message that comes with the AssertionError is kind of useless or time consuming to figure out what is wrong.
当然,在比较两个集合时,AssertionError附带的消息对于找出错误是无用的或耗时的。
Here are two possible solutions that I don't want to use: 这是我不想使用的两个可能的解决方案:
Are there frameworks that have this kind of logging when using equals? 使用equals时是否存在具有这种日志记录的框架?
Are there best practices to handle this problem (or to avoid it in the first place that you don't need this kind of logging)? 是否有最佳实践来解决此问题(或者首先避免您不需要这种日志记录)?
The Spock framework provides this kind of feature. Spock框架提供了这种功能。 You can use any expression as assertion and it will print exactly why it failed:
您可以使用任何表达式作为断言,它会确切显示失败的原因:
assert stack.size() == 2 // this is your assertEquals
And you get: 你会得到:
Condition not satisfied:
stack.size() == 2
| | |
| 1 false
[push me]
We have switched to Spock in place of JUnit in all our projects now because it's so convenient. 现在,我们在所有项目中都已将Spock替换为JUnit,因为它非常方便。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.