简体   繁体   English

如何知道什么导致assertEquals方法在单元测试中失败?

[英]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: 这是我不想使用的两个可能的解决方案:

  1. It's an option to write very specific assertions , but that is too time consuming. 这是写非常具体的断言的一种选择,但这太浪费时间了。
  2. It's also an option to use logging inside the equals methods of your domain. 在域的equals方法使用日志记录也是一种选择。 If equals() returns false, it also prints out the attribute that causes the failure. 如果equals()返回false,则还会打印出导致失败的属性。 I only need to look at my console and see the printed message right before the AssertionError. 我只需要查看控制台,然后在AssertionError之前查看打印的消息。 For collections on the other hand, the equals of the collection is used. 另一方面,对于集合,使用集合的equals。 If for example the lists are not equal because 1 specific object is only present in one of the lists, I would also want that specific log message to appear in the console. 例如,如果列表不相等,因为其中一个列表中仅存在1个特定对象,那么我也希望该特定日志消息出现在控制台中。 But I don't want to write that code myself . 但是我不想自己写那个代码

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM