问题描述
我有一个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.
这是我在 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保留跨线程的Mockito状态时,@ Bean为什么返回模拟工作,而@MockBean不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!