如何测试Spring @EventListener方法? [英] How to test Spring @EventListener method?
问题描述
我有一些活动发布:
@Autowired private final ApplicationEventPublisher publisher;
...
publisher.publishEvent(new MyApplicationEvent(mySource));
我有此事件侦听器:
class MyApplicationEventHandler {
@Autowired SomeDependency someDependency;
@EventListener public void processEvent(final MyApplicationEvent event) {
// handle event...
}
}
我需要使用EasyMock对其进行测试.有没有一种简单的方法可以在测试中发布某些内容并断言我的事件侦听器做了什么?
I need to test it using EasyMock. Is there a simple way to publish something in test and assert that my event listener did something?
我试图创建这样的模拟测试:
I tried to create mock test like this:
// testing class
SomeDependency someDependency = mock(SomeDependency.class);
MyApplicationEventHandler tested = new MyApplicationEventHandler(someDependency);
@Autowired private final ApplicationEventPublisher publisher;
@Test
public void test() {
someDependency.doSomething(anyObject(SomeClass.class));
replay();
publisher.publishEvent(new MyApplicationEvent(createMySource()));
}
它没有用.
java.lang.AssertionError:
Expectation failure on verify:
SomeDependency.doSomething(<any>): expected: 1, actual: 0
推荐答案
首先,当您使用Spring Boot时,对它们的测试变得非常简单.此测试将启动引导上下文,并注入ApplicationEventPublisher的真实实例,但创建模拟的SomeDependency实例.该测试将发布所需的事件,并验证您的模拟是否按预期被调用.
First, As you're using Spring Boot, the testing of these becomes pretty straightforward. This test will spin up the boot context and inject a real instance of ApplicationEventPublisher, but create a mocked instance of SomeDependency. The test publishes the desired event, and verifies that your mock was invoked as you expected.
@RunWith(SpringRunner.class)
@SpringBootTest
public class EventPublisherTest {
@Autowired
private final ApplicationEventPublisher publisher;
@MockBean
private SomeDependency someDependency;
@Test
public void test() {
publisher.publishEvent(new MyApplicationEvent(createMySource()));
// verify that your method in you
verify(someDependency, times(1)).someMethod();
}
}
这篇关于如何测试Spring @EventListener方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!