如何编写一个JUnit测试来比较两个对象列表的相等性?

时间:2018-08-01 13:42:33

标签: java list object junit

我编写了以下JUnit测试,但是由于我的测试是比较对象引用而不是对象值而失败了:

public class ListSerializerTest {

  private InputStream iStream;
  private ByteArrayOutputStream oStream;

  @Before
  public void init() {
    oStream = new ByteArrayOutputStream();
  }

  List<Position> serialzeAndDeserializeObject(List<Position> positionList) {
    Stream<Position> positionListStream = positionList.stream();
    OutputStreamUtil.<Position> serializeObjectsFromStream(positionList.size(), positionListStream,
        oStream, PositionSerializer::serialize);
    iStream = new ByteArrayInputStream(oStream.toByteArray());
    List<Position> deserializedPositionList = new ArrayList<>();
    Consumer<Position> PositionListConsumer = position -> deserializedPositionList.add(position);
    InputStreamUtil.<Position> deserializeObjectsToConsumer(iStream, PositionListConsumer,
        PositionSerializer::deserialize);
    return deserializedPositionList;
  }

  @Test
  public void Equals_equal() {
    List<Position> positionList = new ArrayList<Position>();
    for (int i = 0; i < 10; i++) {
      double x = Math.random();
      double y = Math.random();
      Position positionObject = new Position(x, y);
      positionList.add(positionObject);
    }
    List<Position> deserializedPositionList = serialzeAndDeserializeObject(positionList);
    assertThat(deserializedPositionList).isEqualTo(positionList);
  }
}

如何使其比较对象值而不是对象引用?

1 个答案:

答案 0 :(得分:2)

您很可能在hashCode()类中缺少正确的equals()Position。您需要像这样的测试:

Position a = new Position(1d, 1d);
Position b = new Position(1d, 1d);
assertThat(a).isEqualTo(b);

您对断言的假设不正确,您的测试未使用引用进行比较。在AssertJ中,{p}中的isEqualTo()方法:

assertThat(deserializedPositionList).isEqualTo(positionList);
  

验证实际值等于给定值。

可通过在幕后调用ArrayList.equals()方法来执行。要比较列表的引用,请使用isSameAs()

assertThat(deserializedPositionList).isSameAs(positionList);
  

验证实际值是否与给定值相同,即使用==比较

正在像==一样使用deserializedPositionList == positionList运算符执行检查。