How do I assert equality on two classes without an equals method?

后端 未结 23 1572
臣服心动
臣服心动 2020-11-28 05:20

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.

I can do multiple asserts:

23条回答
  •  温柔的废话
    2020-11-28 06:02

    Can you put the comparision code you posted into some static utility method?

    public static String findDifference(Type obj1, Type obj2) {
        String difference = "";
        if (obj1.getFieldA() == null && obj2.getFieldA() != null
                || !obj1.getFieldA().equals(obj2.getFieldA())) {
            difference += "Difference at field A:" + "obj1 - "
                    + obj1.getFieldA() + ", obj2 - " + obj2.getFieldA();
        }
        if (obj1.getFieldB() == null && obj2.getFieldB() != null
                || !obj1.getFieldB().equals(obj2.getFieldB())) {
            difference += "Difference at field B:" + "obj1 - "
                    + obj1.getFieldB() + ", obj2 - " + obj2.getFieldB();
            // (...)
        }
        return difference;
    }
    

    Than you can use this method in JUnit like this:

    assertEquals("Objects aren't equal", "", findDifferences(obj1, obj));

    which isn't clunky and gives you full information about differences, if they exist (through not exactly in normal form of assertEqual but you get all the info so it should be good).

提交回复
热议问题