为什么@Bean 返回模拟工作但@MockBean 在春季启动测试中跨线程保留 Mockito 状态时不起作用? [英] Why does @Bean returning a mock work but @MockBean doesn't work when it comes to preserving Mockito state across threads in a spring boot test?

查看:27
本文介绍了为什么@Bean 返回模拟工作但@MockBean 在春季启动测试中跨线程保留 Mockito 状态时不起作用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 JMS Spring Boot 项目,我正在尝试使用我的 JMS 侦听器进行集成测试,并且我使用 mockito 模拟来模拟带有外部服务调用的 bean.

I have a JMS Spring Boot project, and I am trying to integration test with my JMS Listener, and I use mockito mocks to mock out beans with external service calls.

在测试期间,我遇到了一个问题,即 Mockito.when/thenReturn 在我的 JMS 侦听器中返回 null.

During testing, I was having an issue where Mockito.when / thenReturn returns a null within my JMS listener.

我对有问题的服务使用 @MockBean,但是当我使用 @Bean 并返回 Mockito.mock 时,我没有在我的模拟中不再获得 null 值.

I was using @MockBean for the service in question, but when I used @Bean and return Mockito.mock, I was no longer getting a null value in my mock.

有谁知道为什么像这样定义的 @MockBean 会有区别

Does anyone know why there would be a difference between @MockBean defined like this

@MockBean
private Service myService;

@Bean这样定义

@Bean
private Service myService(){
   return Mockito.mock(Service.class);
}

在测试 JMS 侦听器时?请注意,spring 测试将在 thread[main] 中进行,JMS 监听器将在 thread[DefaultMessageListenerContainer-1] 上进行监听.

when it comes to testing JMS Listeners? Please note that the spring test will be in thread[main], and the JMS listener will be listening on thread[DefaultMessageListenerContainer-1].

推荐答案

我发现了这个问题.事实证明,Spring MockBean 在测试完成后会自动重置.对于我的 JMS 侦听器,事实证明带有测试的主线程已经完成并且模拟已经重置.对于看到相同行为的其他人,请确认您的主测试线程尚未完成.

I figured out the issue with this. It turns out that Spring MockBean automatically resets after the test is completed. In the case of my JMS listener, it turns out that the main thread with the test has already completed and the mock has reset. For anyone else seeing the same behaviour, please validate that your main test thread has not completed yet.

这是我在 MockBean.java

/**
     * The reset mode to apply to the mock bean. The default is {@link MockReset#AFTER}
     * meaning that mocks are automatically reset after each test method is invoked.
     * @return the reset mode
     */
    MockReset reset() default MockReset.AFTER;

这篇关于为什么@Bean 返回模拟工作但@MockBean 在春季启动测试中跨线程保留 Mockito 状态时不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆