如何在没有 equals 方法的情况下在两个类上断言相等? [英] How do I assert equality on two classes without an equals method?

查看:36
本文介绍了如何在没有 equals 方法的情况下在两个类上断言相等?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个没有 equals() 方法的类,它没有源.我想在该类的两个实例上断言相等.

Say I have a class with no equals() method, to which do not have the source. I want to assert equality on two instances of that class.

我可以做多个断言:

assertEquals(obj1.getFieldA(), obj2.getFieldA());
assertEquals(obj1.getFieldB(), obj2.getFieldB());
assertEquals(obj1.getFieldC(), obj2.getFieldC());
...

我不喜欢这个解决方案,因为如果早期断言失败,我不会得到完整的平等图.

I don't like this solution because I don't get the full equality picture if an early assert fails.

我可以自己手动比较并跟踪结果:

I can manually compare on my own and track the result:

String errorStr = "";
if(!obj1.getFieldA().equals(obj2.getFieldA())) {
    errorStr += "expected: " + obj1.getFieldA() + ", actual: " + obj2.getFieldA() + "
";
}
if(!obj1.getFieldB().equals(obj2.getFieldB())) {
    errorStr += "expected: " + obj1.getFieldB() + ", actual: " + obj2.getFieldB() + "
";
}
...
assertEquals("", errorStr);

这给了我完整的平等图,但很笨重(我什至没有考虑可能的空问题).第三种选择是使用 Comparator,但 compareTo() 不会告诉我哪些字段不相等.

This gives me the full equality picture, but is clunky (and I haven't even accounted for possible null problems). A third option is to use Comparator, but compareTo() will not tell me which fields failed equality.

有没有更好的做法可以从对象中获得我想要的东西,而不需要子类化和覆盖等号(呃)?

Is there a better practice to get what I want from the object, without subclassing and overridding equals (ugh)?

推荐答案

这里有很多正确答案,但我也想添加我的版本.这是基于 Assertj.

There is many correct answers here, but I would like to add my version too. This is based on Assertj.

import static org.assertj.core.api.Assertions.assertThat;

public class TestClass {

    public void test() {
        // do the actual test
        assertThat(actualObject)
            .isEqualToComparingFieldByFieldRecursively(expectedObject);
    }
}

更新:在 assertj v3.13.2 中,正如 Woodz 在评论中指出的那样,此方法已被弃用.目前的建议是

UPDATE: In assertj v3.13.2 this method is deprecated as pointed out by Woodz in comment. Current recommendation is

public class TestClass {

    public void test() {
        // do the actual test
        assertThat(actualObject)
            .usingRecursiveComparison()
            .isEqualTo(expectedObject);
    }

}

这篇关于如何在没有 equals 方法的情况下在两个类上断言相等?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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