[英]How to inject mock collection by annotation with Mockito
我创建了一个带有两个参数的参数化类。 一种是字符串类型,另一种是抽象类的列表类型。 类构造函数看起来像下面的代码。
public TestService(Tenant tenant, List<AbstractService> testServices) {
testServicesMap = testServices.stream().collect(Collectors.toMap(AbstractService::getType, Function.identity()));
}
现在我想为这个类编写 Junit 测试用例,为此我有以下代码。
@Mock
protected Tenant tenant;
@Mock
private List<AbstractService> testServices;
@InjectMocks
private TestService testService;
@Before
public void setup() {
testServices.add(new JobService(new JobEventService()));
testServices.add(new ApplicationService(new ApplicationEventService()));
testServices.add(new UserService(new UserEventService()));
// notificationService = new NotificationService(tenant, notificationServices);
// MockitoAnnotations.initMocks(notificationService);
}
我还尝试启用两条注释行,但现在可以使用了。 以下是系统在启动时抛出的错误。
org.mockito.exceptions.base.MockitoException:
Cannot instantiate @InjectMocks field named 'notificationService' of type 'class com.test.TestService'.
You haven't provided the instance at field declaration so I tried to construct the instance.
However the constructor or the initialization block threw an exception : `null`.
有人可以帮忙吗?
您将模拟与真实对象混合在一起,因为您创建了一个列表模拟,然后在该列表上调用add
方法,然后您希望stream()
像往常一样工作。
Mockito mocks 默认不做任何事情,所以你必须告诉它:
Mockito.when(testServices.stream())
.thenReturn(Stream.of(new JobService(new JobEventService())));
或者在您的情况下更好的是从testServices
删除@Mock
并为其分配一个新的ArrayList
问题是您尝试模拟列表,并且调用了 list.stream(),它在模拟中默认返回 null。
重复问题的常见解决方案是使用列表的@Spy。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.