【问题标题】:How to Mock Optional Autowired field如何模拟可选的自动装配字段
【发布时间】:2021-11-08 10:50:51
【问题描述】:

我正在尝试使用 Mockito 进行单元测试,但我找不到任何方法来模拟我的构造函数的可选自动装配字段。

这是我的构造函数:

@Autowired
public BatchInputManager(
    BatchInputContentRepository batchInputContentRepository,
    Optional<List<BatchInputExecutor>> batchInputExecutors) {
    // ...
}

这是我尝试模拟这些字段的方法:

@InjectMocks
BatchInputManager batchInputManager;
@Mock
BatchInputContentRepository batchInputContentRepository;
@Mock
List<BatchInputExecutor> executors;

作为记录,BatchInputExecutor 类是一个抽象类,我在测试中定义了一个扩展它的类。
当我运行我的代码时,应该包含BatchInputExecutor 的所有扩展类的可选不是空的,它是空的;并且存储库不为空。
我应该如何在构造函数中模拟可选字段的值?

【问题讨论】:

    标签: java spring mockito optional autowired


    【解决方案1】:

    我会在 JUnit 测试的 @BeforeEach/@BeforeAll 方法中设置模拟。

    @BeforeEach
    public void mocking(){
        var repoMock = ... mock repo ..
        var executorMock = mock(BatchInputExecutor.class)
        // configure executorMock here 
        var batchInputExecutors = Optional.of(List.of(executorMock))
        var batchInputManager = new BatchInputManager()
        ... set the class level fields here .. 
    }
    

    【讨论】:

    • 所以你告诉我这里没有办法使用 Mockito 的注释,我必须手动设置我的模拟?
    • 你可以这样尝试... @Mock Optional> executors;但是,无论如何您都需要以某种方式配置模拟
    • 我们无法模拟可选字段,因为它会抛出错误“无法模拟/监视类 java.util.Optional”
    • 那么它的唯一手册
    【解决方案2】:

    如果你真的想在这种情况下使用 Mockito 的注解:

    改变这个

    @Mock
    List<BatchInputExecutor> executors;
    

    到这里

    @Mock
    Optional<List<BatchInputExecutor>> executors;
    

    并配置 mockito 以支持 final 类和方法。看到这个https://stackoverflow.com/a/40018295/10744129

    【讨论】:

    • 感谢您的支持,我现在可以在测试中使用注释处理 Optional。它现在导致两个问题:此代码在我的构造函数中返回 null:executors.orElseGet(ArrayList::new) 并且扩展 BatchInputContentExecutor 的已定义 mockExecutor 不在 Mocked 列表中
    猜你喜欢
    • 1970-01-01
    • 2014-06-03
    • 1970-01-01
    • 2016-01-22
    • 2013-10-18
    • 1970-01-01
    • 1970-01-01
    • 2016-02-23
    • 1970-01-01
    相关资源
    最近更新 更多