为什么在春季启动测试中@Bean保留跨线程的Mockito状态时,@ Bean为什么返回模拟工作,而@MockBean不起作用? [英] 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?

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

问题描述

我有一个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侦听器时?请注意,弹簧测试将在 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.

这是我在 查看全文

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