类 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/