我创建了一个带有两个参数的参数化类。一种是字符串类型,另一种是抽象类的列表类型。类构造函数如下代码所示。
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 模拟默认情况下不执行任何操作,因此您必须告诉它:
Mockito.when(testServices.stream())
.thenReturn(Stream.of(new JobService(new JobEventService())));
或者在你的情况下更好的是从testServices
中删除@Mock
并为其分配一个新的ArrayList
关于java - 如何使用 Mockito 通过注释注入(inject)模拟集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60170015/