断言Set包含具有返回给定值的方法的对象

时间:2015-07-10 18:12:27

标签: java junit hamcrest

A类有一个方法getId(),它返回一个String。

B类有一个方法getCollection(),它返回一个Collection(订单未定义)

我希望我的测试验证返回的集合包含A的实例,每个实例都返回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()
    }

}

我只能想到一些在这里真的不优雅的东西。我目前正在使用JUnit / Hamcrest / Mockito。如果最好的解决方案意味着库,这不是问题

4 个答案:

答案 0 :(得分:2)

Java-8解决方案,它够优雅吗?

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

    }

}

编辑:

AssertJ:ReminderSet

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

答案 1 :(得分:2)

您可以使用Hamcrest的(<a href="#)([^"]+)("{1})> $1" onclick="alert('yay')"> 匹配器。

containsInAnyOrder

如果发生故障,将打印信息性消息。例如。如果Collection有第四个元素,标识为hasProperty

@Test
public void test () {
    B b = ( ... )
    Collection<A> collection = b.getCollection();
    assertThat(collection, containsInAnyOrder(
        Matchers.<A>hasProperty("id", equalTo("id1")),
        Matchers.<A>hasProperty("id", equalTo("id2")),
        Matchers.<A>hasProperty("id", equalTo("id3"))));
}

答案 2 :(得分:-1)

使用collection.contains(Object o)方法 但是你应该为A类重写equals()和hashCode()以获得对象的预期结果

答案 3 :(得分:-1)

您可以使用Mockito模拟界面A.

@Test
public void test () {
    //given: we have our expected and actual lists.
    List<String> expectedResult = Arrays.asList("id1","id2","id3");

    //build our actual list of mocked interface A objects.
    A a1 = mock(A.class);
    when(a1.getId()).thenReturn("id1");
    A a2 = mock(A.class);
    when(a2.getId()).thenReturn("id2");
    A a3 = mock(A.class);
    when(a3.getId()).thenReturn("id3");
    B b = mock(B.class);
    Collection<A> actualResult = Arrays.asList(a1, a2,a3);

    //when: we invoke the method we want to test.
    when(b.getCollection()).thenReturn(actualResult);

    //then: we should have the result we want.
    assertNotNull(actualResult);
    assertEquals(3, actualResult.size());
    for (A a : actualResult) assertTrue(expectedResult.contains(a.getId()));

}