Search code examples
javastringjunitassert

How to check all fields in 2 objects are equal using reflectionEquals?


I am writing a JUnit test and I want to test that all the fields in 2 objects are equal.

I have tried the following:

    @Test
    public void testPersonObjectsAreEqual(){
      
        Person expectedPerson = new Person("100100", "sampleName", "sampleAddress");
        Person actualPersonReturned = repository.getPersonById("100100");
        
        Assert.assertTrue(EqualsBuilder.reflectionEquals(expectedPerson, actualPersonReturned));
    }

But the test is failing, even though the fields in the 2 objects are the same.

They are both have: 100100 , sampleName and sampleAddress


Solution

  • In your example, you need to override the equals method in your class Person (returning true if the attributes of the Person object are all equal). For example:

    public class Person {
    
        private String name;
        private String surname;
    
        @Override
        public boolean equals(Object obj) {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            Person other = (Person) obj;
            if (name == null) {
                if (other.name != null)
                    return false;
            } else if (!name.equals(other.name))
                return false;
            if (surname == null) {
                if (other.surname != null)
                    return false;
            } else if (!surname.equals(other.surname))
                return false;
            return true;
        }
    
    }
    

    You can do it automatically with an IDE, the previous snippet was generated automatically with Eclipse.