Wednesday, May 21, 2014

Moqing Prism's EventAggregator

Writing unit tests against the Prism EventAggregator using Moq should be easy right?  After all there is the IEventAggregator interface, and all of our events are separate classes.

Below are two examples.  Example 1 verifies a certain event is published twice.
That is fairly simple, and it works!   Great, so what is the problem?

Example 2 shows how to trigger an event using Moq.  Imagine you have a subscription to an event, and the Action in the Subscribe() method is private.  Using Moq the event needs to be published and the system under test then needs to be examined for a change in state.

The key to example two seems to be this, a real event must be used not a mocked event.  I was able to find two separate examples for Rhino Mocks and adapt them to Moq. RhinoMock:Exp1 RhinoMock:Exp2

As a side note there is allot of information and miss-information surrounding Moq and IEventAggregator.

Stack Overflow: Moq Event Aggregator is it Possible?

Stack Overflow: Mocking Prism Event Aggregator using Moq for Unit Testing

Stack Overflow: How to verify Event Subscribed using Moq

CodePlex: Mocking Event Aggregator with MOQ

Note: As pointed out in the Stack Overflow post titled How to verify Event Subscribed using Moq, the only virtual call to Subscribe takes lots of parameters, so makes a messy looking test.  Not to mention even then its not working for me, need to get the call back parameters right, the parameters in the SO example make my test error.

No comments:

Post a Comment