如何测试复杂对象图的相等性? [英] How to test for equality of complex object graphs?

查看:93
本文介绍了如何测试复杂对象图的相等性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个单元测试想要比较两个复杂的对象是否相等。对象包含许多其他深层嵌套的对象。所有对象的类都已正确定义 equals()方法。

Say I have a unit test that wants to compare two complex for objects for equality. The objects contains many other deeply nested objects. All of the objects' classes have correctly defined equals() methods.

这并不难:

@Test
public void objectEquality() {
    Object o1 = ...
    Object o2 = ...

    assertEquals(o1, o2);
}

麻烦的是,如果对象不相等,你得到的只是一个失败,没有指示对象图的哪个部分不匹配。调试这可能是痛苦和令人沮丧的。

Trouble is, if the objects are not equal, all you get is a fail, with no indication of which part of the object graph didn't match. Debugging this can be painful and frustrating.

我目前的方法是确保所有实现 toString(),以及然后像这样比较相等:

My current approach is to make sure everything implements toString(), and then compare for equality like this:

    assertEquals(o1.toString(), o2.toString());

这样可以更轻松地追踪测试失败,因为像Eclipse这样的IDE有一个特殊的可视比较器用于显示失败测试中的字符串差异。基本上,对象图以文本方式表示,因此您可以看到差异的位置。只要 toString()编写得很好,它就会很好。

This makes it easier to track down test failures, since IDEs like Eclipse have a special visual comparator for displaying string differences in failed tests. Essentially, the object graphs are represented textually, so you can see where the difference is. As long as toString() is well written, it works great.

尽管如此,它有点笨拙。有时你想设计toString()用于其他目的,比如日志记录,也许你只想渲染一些对象字段而不是所有对象字段,或者根本没有定义toString(),依此类推。

It's all a bit clumsy, though. Sometimes you want to design toString() for other purposes, like logging, maybe you only want to render some of the objects fields rather than all of them, or maybe toString() isn't defined at all, and so on.

我正在寻找更好的比较复杂对象图的方法。有什么想法吗?

I'm looking for ideas for a better way of comparing complex object graphs. Any thoughts?

推荐答案

你可以做的是使用 XStream ,然后使用 XMLUnit 进行比较关于XML。如果它们不同,那么您将获得上下文信息(以XPath,IIRC的形式),告诉您对象的不同之处。

What you could do is render each object to XML using XStream, and then use XMLUnit to perform a comparison on the XML. If they differ, then you'll get the contextual information (in the form of an XPath, IIRC) telling you where the objects differ.

例如。来自XMLUnit doc:

e.g. from the XMLUnit doc:

Comparing test xml to control xml [different] 
Expected element tag name 'uuid' but was 'localId' - 
comparing <uuid...> at /msg[1]/uuid[1] to <localId...> at /msg[1]/localId[1]

注意XPath指示不同元素的位置。

Note the XPath indicating the location of the differing elements.

可能不会很快,但这可能不是单元测试的问题。

Probably not fast, but that may not be an issue for unit tests.

这篇关于如何测试复杂对象图的相等性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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