I have a simple Guava EventBus with one simple event and one simple listener. My question is what is the test pattern to check if the listener method is invoked once the event is posted.
2 Answers
I would suggest that testing that the EventBus works properly is not a UNIT test you should be writing. One of the advantages of using a library (at least of using one you trust) is that the unit tests have been written by the library provider. So please don't waste your time verifying that the Google folks wrote EventBus properly. To write unit tests of your system the EventBus should be mocked and therefore your listener would not be invoked. This is one of the advantages of using a message bus, it allows for isolation of separate application concerns which allows for easier unit testing.
When you are ready to do so, it would be an integration test that tests that the entire system works together. In some cases this might also be written in JUnit but don't think that it is a unit test. How to do this depends on your system. You might load up a Spring context into a JUnit test or you might deploy the application and run tests against it.

- 32,493
- 6
- 77
- 98
-
3If your code conditionally publishes to an EventBus, you need to be able to verify that during your test, the EventBus indeed fired the desired event with the correct parameters. – Bill Poitras Nov 13 '15 at 18:51
This kind of testing is usually done by using a mocking framework like Mockito. Create a mock listener, register it with the event bus, fire the event, and verify that the listener method got invoked.
Find here a very basic example on how to create a mock and how to verify interactions to it.

- 17,223
- 4
- 51
- 48
-
I know mockito,I didn't know it can be use in the cases like this. I will think about it. many thx. – speedingdeer May 07 '13 at 09:23
-
2Not sure this will work - EventBus scans registered objects for a @Subscribe annotation, which possibly may not be present on the mocked object. – pauljwilliams May 07 '13 at 10:29