Search code examples
javajunithamcrest

Asserting that a Set contains objects with methods that return given values


Class A has a method, getId(), which returns a String.

Class B has a method, getCollection(), that returns a Collection (the order is undefined)

I want my test to validate that the returned collection contains instances of A, who each return expected values for getId()

public interface A {
    String getId ();
}

public interface B {
    Collection<A> getCollection ();
}

public class BTest {

    @Test
    public void test () {
        B b = ( ... )
        Collection<A> collection = b.getCollection();
        assertEquals(3, collection.size());

        String expId1 = "id1";
        String expId2 = "id2";
        String expId3 = "id3";

        // There should be 3 A's in this collection, each returning
        // one of the expected values in their getId()
    }

}

I can only think of something that would be really inelegant here. I'm currently using JUnit/Hamcrest/Mockito. If the nicest solution means library, that's not a problem


Solution

  • Java-8 solution, is it enough elegant?

    public class BTest {
    
        @Test
        public void test () {
            B b = ( ... )
            Set<String> expectIds = new HashSet<>(Arrays.asList("id1","id2","id3"));
            Collection<A> collection = b.getCollection();
            Set<String> ids = collection.stream().map(a->a.getId()).collect(Collectors.toSet());
    
            assertEquals(3, collection.size());
            assertEquals(expectIds, ids);
    
        }
    
    }
    

    EDITED:

    AssertJ: http://joel-costigliola.github.io/assertj/assertj-core-features-highlight.html

    public class BTest {
    
        @Test
        public void test () {
            B b = ( ... )
            Collection<A> collection = b.getCollection();
    
            assertEquals(3, collection.size());
            assertThat(collection).extracting("id").contains("id1","id2","id3");
        }
    }