Are you using Guava’s event bus in your Java project? Do you need to test and validate interactions with the event bus but are having trouble? Mockito can help you out here with just a few lines of code.
Assume you have two event types. We’ll call them
UnwantedEvent. In your test you can use Mockito to create a mock event bus like this:
Then you can use Mockito’s
doAnswer functionality to intercept all interactions with the event bus and do something like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
When you use your event bus in your tests now you’ll be counting the number of times
UnwantedEvent are published (you do need to make those variables accessible outside the scope of this anonymous
You’ll also be throwing exceptions if you see any other kinds of events that you didn’t expect so you can fail immediately if there is additional unwanted behavior going on. Naturally you can leave the else part out and ignore other events completely too.
Using this simple pattern I’ve been able to debug, test, and be confident in the implementation of several projects that use the Guava event bus.
Do you have any tricks or tips related to this article? Is there a better or easier way to do what I’m doing here? Did this get you out of a bind? Post in the comments!