断言两个 java bean 是等效的

2022-09-04 05:50:14

这个问题很接近,但仍然不是我想要的。我想以一般的方式断言两个bean对象是等效的。如果不是,我想要一条详细的错误消息来解释差异,而不是布尔值“等于”或“不等于”。


答案 1
import static org.hamcrest.beans.SamePropertyValuesAs.samePropertyValuesAs;
import static org.junit.Assert.assertThat;

@Test
public void beansAreTheSame(){
    MyDomianClass bean1 = new MyDomainClass();
    MyDomianClass bean2 = new MyDomainClass();
    //TODO - some more test logic

    assertThat(bean1, samePropertyValuesAs(bean2));
}

答案 2

我建议你使用unitils库:

http://www.unitils.org/tutorial-reflectionassert.html

public class User {

    private long id;
    private String first;
    private String last;

    public User(long id, String first, String last) {
        this.id = id;
        this.first = first;
        this.last = last;
    }
}
User user1 = new User(1, "John", "Doe");
User user2 = new User(1, "John", "Doe");
assertReflectionEquals(user1, user2);

另请参阅: