java - 如何使用 Mockito 通过注释注入(inject)模拟集合

标签 java mockito junit4

我创建了一个带有两个参数的参数化类。一种是字符串类型,另一种是抽象类的列表类型。类构造函数如下代码所示。

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/

相关文章:

java - 将 websocket 连接同步到同一端点

java - 在 Java 中模拟链式调用的最佳解决方案

为 Maven 项目运行 JUNIT mockito 和 powermock 时出现 java.lang.VerifyError

java - Mockito 无法模拟 Rest API 调用

java - 即使我使用 powermockito 来模拟类,也会出现 "Mockito cannot mock this class"错误

java - SimpleDateFormat 对同一日期字符串的解析和格式化给出了不同的结果

java - 为什么java中的toString方法似乎不适用于数组

java - JTextField 在使用自定义 TrueType 字体时裁剪文本。如何让它正常显示文字?

spring - 如何使用 Dbunit 测试没有 Hibernate 实体的表的 Dao

java - 带有静态类列表的 Junit SuiteClasses