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

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

    This is a generic compare method , that compares two objects of a same class for its values of it fields(keep in mind those are accessible by get method)

    public static  void compare(T a, T b) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        AssertionError error = null;
        Class A = a.getClass();
        Class B = a.getClass();
        for (Method mA : A.getDeclaredMethods()) {
            if (mA.getName().startsWith("get")) {
                Method mB = B.getMethod(mA.getName(),null );
                try {
                    Assert.assertEquals("Not Matched = ",mA.invoke(a),mB.invoke(b));
                }catch (AssertionError e){
                    if(error==null){
                        error = new AssertionError(e);
                    }
                    else {
                        error.addSuppressed(e);
                    }
                }
            }
        }
        if(error!=null){
            throw error ;
        }
    }
    

提交回复
热议问题