Mocking Prism's EventAggregator

EventAggregator is the Prism incarnation of the publish-subscribe pattern. Message classes are sent between components, keeping the components decoupled.

Writing unit tests against the Prism EventAggregator using Moq should be easy right? The IEventAggregator interface is provided by the Prism framework. We know interfaces make things testable. So yes this all should be possible. However, there is a good deal of confusion around this.

StackOverflow: Moq Event Aggregator is it possible? StackOverflow: Mocking Prism Event Aggregator using moq for unit testing StackOverflow: How to verify event subscribed using moq?

It's not as confusing or complex as confusion can make it :)

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 needs to be examined for a state change.

public void EventAggregator_ReceivesUpdatedUnitsEvent_CallsOnUnitsUpdated(){  

  //Use the real event not a mock  
  _updateUnitsEvent = new UpdatedUnitsEvent(); 
  //Setup the mock EventAggregator to return the event  
  _mockEventAggregator.Setup(x => x.GetEvent<UpdatedUnitsEvent>())
  _mockUnits.Object.DensitySolid = DensitySolidSymbols.KgCm3; 

  //Trigger the event by publishing our payload   

  _mockEventAggregator.Verify(x => x.GetEvent<UpdatedUnitsEvent>(), 
  //Verify using Moq   
  var vm = _materialMasterVm.MaterialModels.Current as MaterialViewModel;
  //Check State 
  Assert.AreEqual(DensitySolidSymbols.KgCm3, vm.Density.UserUnitType); 

Don't make the mistake of trying to use a mock for the message class.

Happy Coding!