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

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

    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);
        }
    }
    

    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);
        }
    
    }
    

提交回复
热议问题