Search code examples
javajunitmockitohamcrest

Compare objects's properties values but not objects type


is possible to compare objects of two different types compare with mockito or hamcrest ? For example below I show examples of my objects.

ObjectA:

public class ObjectA {
    private Long id;
    private String name;
    private AddressA address
    // getters and setters
}

ObjectB:

public class ObjectB {
    private Long id;
    private String name;
    private AddressB address
    // getters and setters
}

Objects AddressA and AddressB are also with same named properties, but only different types. Is it possible, and if yes how? Thanks.


Solution

  • Using hamcrest API, you can achieve it by following

    ObjectA A = new ObjectA(1, "ABC", new AddressA("jkl"));
    ObjectB B = new ObjectB(1, "PQR", new AddressB("xyz"));
    
    assertThat(A, hasProperty("id", equalTo(B.getId())));
    assertThat(A, hasProperty("name", equalTo(B.getName())));
    assertThat(A.getAddressA(), hasProperty("address", equalTo(B.getAddressB().getAddress())));