How can I compare POJOs by their fields reflectively

Gaurav Varma picture Gaurav Varma · Dec 6, 2014 · Viewed 10.1k times · Source

I am basically looking for a unit testing framework, which I can use to compare POJOs which don't override equals and hascode methods. I had a look at JUnit, Test NG and Mockito but they don't seem to solve the purpose.

For example consider the code below :

public class CarBean { 

    private String brand;
    private String color;

    public CarBean (){
    }

    public CarBean (String brand, String color){
        this.brand= brand;
        this.color= color;
    }

    /**
     * @return the brand
     */
    public String getBrand() {
        return brand;
    }

    /**
     * @param the brand to set
     */
    public void setBrand(String brand) {
        this.brand= brand;
    }

    /**
     * @return the color
     */
    public String getColor() {
        return color;
    }

    /**
     * @param the color to set
     */
    public void setColor(String color) {
        this.color= color;
    }
}

The POJO CarBean represents a real world car. It has two parameters, brand and color. Now, suppose you have two car objects as below :

CarBean car1 = new CarBean("Ford","Black");
CarBean car2 = new CarBean("Ford","Black");

Both the objects have same parameter values. But when you compare this using equals, it returns false :

car1.equals(car2); // This returns false

Now I need to unit test a method that returns CarBean object. In this scenario I would either need to compare the carbean attributes one by one or I would need to implement equals() and hashcode() methods.

So my question is - Is there already a unit testing framework which can handle this ?

Answer

Deepesh kumar picture Deepesh kumar · Jun 23, 2016

Override the toString() method in your pojo class like below

@Override
public String toString() {
    return "brand: " + this.brand + ",color: " + this.color;
}


car1.toString().equals(car2.toString()); //It will return true if both objects has same values

In case you have large nos of parameter i will suggest you to go with bellow code

public static boolean comparePOJO(Object obj1, Object obj2) {
    return new Gson().toJson(obj1).equals(new Gson().toJson(obj2));
}
comparePOJO(car1,car2); //It will return true