我有一个抽象类 AbstractService 和几个扩展这个抽象类的类:
然后我有一个 ServiceFactory 根据我传递的参数返回一个包含一些服务的通用列表:
public class ServiceFactory {
public List<? extends AbstractService> getServices(final MyParameter param) {
// Service is an interface implemented by AbstractService
List<Service> services = new ArrayList<>();
for (Foo foo : param.getFoos()) {
services.add(new AService(foo.getBar()));
}
// creates the rest of the services
return services;
}
}
在我的 UnitTest 中,我想验证我的服务列表是否正好包含 3 个 AService 子类型。我现在这样做的方式是:
@Test
public void serviceFactoryShouldReturnAServiceForEachFoo() {
// I'm mocking MyParameter and Foo here
Mockito.when(param.getFoos()).thenReturn(Arrays.asList(foo, foo, foo);
AService aservice = new AService(foo);
List<AService> expectedServices = Arrays.asList(aservice, aservice, aservice);
List<? extends AbstractService> actualServices = serviceFactory.getServices();
assertTrue(CollectionUtils.isSubCollection(expectedServices, actualServices));
}
当 actualServices 包含少于 3 个 Aservice 时,测试正确失败。这个解决方案唯一的问题是如果actualServices包含超过3个AService,测试通过...
有没有一种方法可以做到这一点,或者我应该使用循环自己实现它?