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

后端 未结 23 1658
臣服心动
臣服心动 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:08

    I tried all the answers and nothing really worked for me.

    So I've created my own method that compares simple java objects without going deep into nested structures...

    Method returns null if all fields match or string containing mismatch details.

    Only properties that have a getter method are compared.

    How to use

            assertNull(TestUtils.diff(obj1,obj2,ignore_field1, ignore_field2));
    

    Sample output if there is a mismatch

    Output shows property names and respective values of compared objects

    alert_id(1:2), city(Moscow:London)
    

    Code (Java 8 and above):

     public static String diff(Object x1, Object x2, String ... ignored) throws Exception{
            final StringBuilder response = new StringBuilder();
            for (Method m:Arrays.stream(x1.getClass().getMethods()).filter(m->m.getName().startsWith("get")
            && m.getParameterCount()==0).collect(toList())){
    
                final String field = m.getName().substring(3).toLowerCase();
                if (Arrays.stream(ignored).map(x->x.toLowerCase()).noneMatch(ignoredField->ignoredField.equals(field))){
                    Object v1 = m.invoke(x1);
                    Object v2 = m.invoke(x2);
                    if ( (v1!=null && !v1.equals(v2)) || (v2!=null && !v2.equals(v1))){
                        response.append(field).append("(").append(v1).append(":").append(v2).append(")").append(", ");
                    }
                }
            }
            return response.length()==0?null:response.substring(0,response.length()-2);
        }
    

提交回复
热议问题