我有:
List<SlaveEntityDTO> result = Jsoner.JsonToSlaveEntityDTO(json);
List<SlaveEntityDTO> result1 = entitiesDTOList;
结果和 result1 的字段值相同:
当我运行 Assert.assertEquals(result, result1);
时,我收到以下消息:
java.lang.AssertionError:
Expected :[core.dto.SlaveEntityDTO@6be46e8f, core.dto.SlaveEntityDTO@3567135c]
Actual :[core.dto.SlaveEntityDTO@327471b5, core.dto.SlaveEntityDTO@4157f54e]
那么如何比较 result 和 result1 中字段的值,而不是比较某个对象是否是该对象?
SlaveEntityDTO 是这样的:
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);
}
}
BaseEntityDTO 是这样的:
public abstract class BaseEntityDTO<T> implements Serializable{
private long id;
public abstract T convertToEntity();
}
最佳答案
你的测试看起来不错。 List
接口(interface)定义其 equals
的行为,并且您的调试器显示正在使用 ArrayList
。 ArrayList 是个好东西,所以我们可以假设它的 equals 实现是合法的。
因此,我们可以得出结论,您的 SlaveEntityDTO
类不会覆盖 Object#equals(Object)
或者它以一种您没有考虑到的方式这样做(这可能意味着它的实现不正确)。
您可以通过覆盖 BaseEntityDTO
中的 equals
来修复此问题。这将为每个子类提供equals
的基本行为。
@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);
}
并且不要忘记:hashCode()
必须匹配 equals
的实现!
@Override
public int hashCode() {
return id == null ? 0 : id.hashCode();
}
关于java - JUnit 比较两个实体列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40051646/