Auto Mocking EventAggregator

A general rule about Unit Testing that I try to follow is that a change in the class under test should not break the test, unless the functionality under test is broken. It just makes things more maintainable.

For a long time, when I tested ViewModels I had a method called

StubEvent<TEvent, TPayload>()

This allowed me to stub all the required events for a test and control flow. However, when someone added a new event subscription or publication into the ViewModel,  the tests would fail as no one stubbed the new event; breaking the above rule.

The second problem when people started subscribing to Events on the UI Thread using

event.Subscribe(DoSomething, ThreadOption.UIThread);

The UIThread subscription uses Application.Current.Dispatcher which obviously isn’t there in most Unit Tests and so your subscriptions fail.

Enter AutoMockingEventAggregator; this bad boy returns a stubbed version of any event requested and adds a Dispatcher that can be used in testing. Just replace your mocked or concrete IEventAggregator with an instance of AutoMockingEventAggregator and all your testing woes are gone 😉
I even throw in a free AssertSubscriptionWasOnUiThread method.

On a separate note, if you aren’t committed/forced to use Prism’s EventAggregator, have a look at the Observable alternatives such as this one.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s