Search code examples
javajunitaddressbook

JUnit assertEquals failing with HashSet


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.


Solution

  • @Override
    public int hashCode() {
        return zeroBasedIndex;
    }
    

    Overriding hashCode method in Index class sloved it.