Welcome to William's ekasi

[ Log On ]
Using VerifyAllExpectations to test IEventAggregator
2010/01/01
Tags:

It can sometimes be tricky to work out what to mock when testing some of the PRISM components.  One of the tricky ones is the IEventAggregator interface.  Luckily for us, most mocking tools provide some helper methods which make it easy to test that your subscriptions and publications are working correctly.

I’m going to use Rhino Mocks for this post.  Rhino Mocks has an extension method placed on all mocked objects called VerifyAllExpections.  With Rhino Mocks you can create mock objects and then you proceed to tell the mock objects how to behave using the Expect() extension method.  Once you have told the object how to behave, you can use the VerifyAllExpections() extension method to make sure that the methods you expected to be called actually were called.

An example:

Main

Here I want to test that the Subscribe method is called ONCE (and only once) from the constructor.

To do this I need to mock a couple of things out:

  1. I need to mock an IEventAggregator which should expect a call to GetEvent<LoginSuccessful>()
  2. I need to mock out a LoginSuccessful event which should expect ONLY ONE call to Subscribe()

Once we’ve mocked those two and setup the expectations correctly, we can call VerifyAllExpectations to ensure that they were called as we expected them to be called.

Test

And that’s it.  If we change our original code to not call the Subscribe method, the test fails because we told our mock object to expect a call to it.  If we change the code to make two calls to the Subscribe method, the test fails again because of the exception we told our mock object to throw.

Next time: How to check that Publishing works properly

Add Comment

No comments have been posted yet