Unit testing Request Handlers - Goal is to verify the list of commands dispatched for a given request.

I am trying to unit test my request handlers. I use Mockito for my unit tests.

I have a scenario like - the request(webservice) goes to request handler and the request handler dispatches a bunch of commands based on various conditions it check on the request.

I want to unit test this class, so i decided to come up with different requests and send them to this method and then verify the list of commands dispatched, ie. for request 1 it should dispatch commands A and B, for request 2 it should dispatch commands A and C etc.

How can verify the list of commands? i tried using Mockito verify,

verify(commandBus, times(1)).dispatch(new GenericCommandMessage(any(myCommand.class)));
logger.debug(“Verified commandBus.dispatch myCmd is called once”)

I get runtime error because it creates 2 different objects for GenericCommandMessage(1 object while calling the dispatch method and 1 object while checking the verify method) and reports that the 2 objects are different.

I agree to the error, i can use something like,

verify(commandBus, times(1)).dispatch(any(GenericCommandMessage.class));
logger.debug(“Verified commandBus.dispatch is called once”);

but i want to verify that this particular command(myCommand) is dispatched. Please shed some light on how to achieve this. Thanks!

Try having your request handlers use CommandGateway instead of using CommandBus directly. Then mock the CommandGateway interface in your tests.

CommandBus talks about command messages, which have unique identifiers and timestamps etc. That makes command messages difficult to use in tests, because two different command messages that contain the same command object are not equal.

However CommandGateway talks about just plain command objects, which are much easier to use in tests. Just remember to implement equals() properly on your command objects.

Hope this helps,
Richard

Thanks Richard! Will try to implement this solution.