Search code examples
javajunitmockingmockitohamcrest

How to assert a mocked object in a list


I have a Junit test as below:

ClassA a1 = mock(ClassA.class);
ClassB b1 = new B("1", "abcd1");
testClass.addToMap(b1, a1); //add date to map1
ClassA a2 = mock(ClassA.class);
ClassB b2 = new B("2", "abcd2");
testClass.addToMap(b2, a2); //add date to map1
testClass.dropFromMap(); //this will remove the object from map1 and add the ClassA details to a set(set1)

Now the question is that how to verify that the set1 contains both the mocked objects(a1, a2). Something like below:

assertTrue(testClass.set1.contains(a1));
assertTrue(testClass.set1.contains(a2));

Unable to use ArgumentCaptor as I should provide a proper b1 object while adding to map.


Solution

  • If you want to verify that in a single line/statement I would go for the Hamcrest matchers:

    import static org.hamcrest.Matchers.*;
    
    ...
    
    testClass.dropFromMap();
    assertThat(testClass.set1, containsInAnyOrder(a1, a2));
    

    This will make sure that only and exactly these two are in the set.