Issue
I have some event publishing:
@Autowired private final ApplicationEventPublisher publisher;
...
publisher.publishEvent(new MyApplicationEvent(mySource));
I have this event listener:
class MyApplicationEventHandler {
@Autowired SomeDependency someDependency;
@EventListener public void processEvent(final MyApplicationEvent event) {
// handle event...
}
}
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?
EDIT:
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()));
}
It didn't work.
java.lang.AssertionError:
Expectation failure on verify:
SomeDependency.doSomething(<any>): expected: 1, actual: 0
Solution
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();
}
}
Answered By - lane.maxwell
Answer Checked By - Marie Seifert (JavaFixing Admin)