【发布时间】:2021-04-08 04:06:30
【问题描述】:
我有一些活动发布:
@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 对其进行测试。有没有一种简单的方法可以在测试中发布某些内容并断言我的事件侦听器做了什么?
编辑:
我尝试像这样创建模拟测试:
// 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还是vanilla spring?
-
只需注入一个模拟
ApplicationEventPublisher并检查publish方法是否被调用。其他任何事情,您都在测试框架。 -
我使用 SpringBoot 和 EasyMock。
标签: spring unit-testing