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

标签 java junit hamcrest

类 A 有一个方法 getId(),它返回一个字符串。

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。如果最好的解决方案意味着库,那不是问题

最佳答案

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

    }

}

编辑:

断言J: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");
    }
}

关于java - 断言 Set 包含具有返回给定值的方法的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31347560/

相关文章:

java - 如何使用 JMockit 模拟 Calendar.getInstance 方法?

junit - 在 JUnit 中将 "assertTrue"重写为 "assertThat"?

java - JUnit 的 hamcrest 库是否有一个 API 来测试公共(public)变量而不是属性

java - 声纳 "Make transient or serializable"错误

java - 阻止用户电子邮件委托(delegate)确认链接

java - Android 设备 session 管理的最佳实践

java - 单元测试图形

java - 如何在 Spring 项目的终端中更新 pom.xml 属性?

java - 如何使 JUnit 接受任何 Lambda 表达式

java - Hamcrest assertThat - 类型推断