Salem Masoud
Salem Masoud

Reputation: 431

How to write a JUnit test to compare the equality of 2 lists of objects?

I have written the following JUnit test but it was failed because my test is comparing the object references and not the object values:

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);
  }
}

How to make it compare object values instead of object references?

Upvotes: 2

Views: 1213

Answers (1)

Karol Dowbecki
Karol Dowbecki

Reputation: 44932

You are most likely missing correct hashCode() and equals() in the Position class. You need a test like:

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

Your assumption about the assertions is incorrect, your test is not comparing using references. In AssertJ the isEqualTo() method in:

assertThat(deserializedPositionList).isEqualTo(positionList);

Verifies that the actual value is equal to the given one.

which is performed by calling the ArrayList.equals() method under the hood. To compare the lists by their reference one uses isSameAs():

assertThat(deserializedPositionList).isSameAs(positionList);

Verifies that the actual value is the same as the given one, ie using == comparison

which is performing the check with == operator as in deserializedPositionList == positionList.

Upvotes: 2

Related Questions