Cristian Cristian - 1 month ago 19
Java Question

JUnit comparing two Lists of entities

I have:

List<SlaveEntityDTO> result = Jsoner.JsonToSlaveEntityDTO(json);
List<SlaveEntityDTO> result1 = entitiesDTOList;


The result and result1 has the same values for their fields:

enter image description here

When I run
Assert.assertEquals(result, result1);
I am getting the following message:

java.lang.AssertionError:
Expected :[core.dto.SlaveEntityDTO@6be46e8f, core.dto.SlaveEntityDTO@3567135c]
Actual :[core.dto.SlaveEntityDTO@327471b5, core.dto.SlaveEntityDTO@4157f54e]


So how can I compare the values of the fields inside result and result1, instead of comparing if an object is that object?

The SlaveEntityDTO is like this:

public class SlaveEntityDTO extends BaseEntityDTO<SlaveEntity> {

private String ip;
private String macAddress;
private String status;

private List<PositionEntity> positions;

@Override
public SlaveEntity convertToEntity() {
return new ModelMapper().map(this, SlaveEntity.class);
}
}


And the BaseEntityDTO is like this:

public abstract class BaseEntityDTO<T> implements Serializable{

private long id;

public abstract T convertToEntity();
}

Answer

Your test looks fine. The List interface defines the behavior of its equals, and your debugger shows that ArrayList is being used. ArrayList is a good guy, so we can assume that its implementation of equals is legit.

Thus, we can conclude that your SlaveEntityDTO class either does not override Object#equals(Object) or that it does so in a way that you aren't accounting for (which possibly means that it is implementing it incorrectly).

You can fix this by Overriding equals in BaseEntityDTO. This will give basic behavior of equals to every subclass.

@Override
public boolean equals(Object o) {
    if (this == o) return true; // literally the same object.

    if (o == null || getClass() != o.getClass()) return false; // Not correct type.

    BaseEntityDTO that = (BaseEntityDTO) o;
    return this.id == null ? that.id == null : this.id.equals(that.id);
}

And don't forget: hashCode() MUST match the implementation of equals!

@Override
public int hashCode() {
    return id == null ? 0 : id.hashCode();
}