0

I was doing some JUnit tests for the AddressBook and kept failing to implement one of my tests. Here is that test:

@Test
public void parseIndices_collectionWithValidIndices_returnsIndexSet() throws Exception {
    Set<Index> actualIndexSet = ParserUtil.parseIndices(Arrays.asList(VALID_INDEX_1, VALID_INDEX_2));

    Index index = Index.fromOneBased(Integer.valueOf(VALID_INDEX_1));
    Index index2 = Index.fromOneBased(Integer.valueOf(VALID_INDEX_2));
    Set<Index> expectedIndexSet = new HashSet<>();
    expectedIndexSet.add(index);
    expectedIndexSet.add(index2);

    assertEquals(expectedIndexSet, actualIndexSet);
}

The output shows as follows:

Output of running test It shows that they are equal but somehow the assert keeps failing. I then tried asserting the 2 actualIndexSets (as shown below) to see if they would pass the test but it still failed with the same result which is weird.

@Test
public void parseIndices_collectionWithValidIndices_returnsIndexSet() throws Exception {
    Set<Index> actualIndexSet = ParserUtil.parseIndices(Arrays.asList(VALID_INDEX_1, VALID_INDEX_2));
    Set<Index> actualIndexSet2 = ParserUtil.parseIndices(Arrays.asList(VALID_INDEX_1, VALID_INDEX_2));

    Index index = Index.fromOneBased(Integer.valueOf(VALID_INDEX_1));
    Index index2 = Index.fromOneBased(Integer.valueOf(VALID_INDEX_2));
    Set<Index> expectedIndexSet = new HashSet<>();
    expectedIndexSet.add(index);
    expectedIndexSet.add(index2);

    assertEquals(actualIndexSet2, actualIndexSet);
}

The problem here is that something is obviously not right because it fails when I assert 2 sets of the actualIndexSet which are the same given that assert for the Index class is working fine.

Rajdeep
  • 2,246
  • 6
  • 24
  • 51

3 Answers3

0

HashSet overrides equals; it checks if first set contains all from the second set.

The only possible reason is that your Index class is not overriding equals. when method containsAll will be called, it will iterate over all index elements and will check if the result of equals is true.

Adina Rolea
  • 2,031
  • 1
  • 7
  • 16
0

Your problem seems to be the equals method and how it's defined in the Index class.

I would recommend to use a library like apache commons to solve that for you:

CollectionUtils.isEqualCollection(expectedIndexSet, actualIndexSet)
Christian
  • 22,585
  • 9
  • 80
  • 106
0
@Override
public int hashCode() {
    return zeroBasedIndex;
}

Overriding hashCode method in Index class sloved it.

Rajdeep
  • 2,246
  • 6
  • 24
  • 51