Mocking with Moq

Topics: Prism v1
Apr 17, 2009 at 8:06 PM
Hi All,

I'm just writing some tests for my CAL based app and I'm having a few problems.  I'm using Moq to produce the mock objects.  The main issue I'm having is creating a class that subscribes to an event.  The constructor signature on the class is:
public DriveInfoManager(IUnityContainer container, IEventAggregator eventAggregator)
So when I mock this I have the following code:
var mockContainer = new Mock<IUnityContainer>();
var mockEventAggregator = new Mock<IEventAggregator>();
DriveInfoManager driveInfoManager = new DriveInfoManager(mockContainer as IUnityContainer, mockEventAggregator as IEventAggregator);
All is working fine until during the class initialisation it fails (with a helpful disassemble dialog from xUnit) on this line:
_eventAggregator.GetEvent<MonitorDrivesEvent>().Subscribe(OnMonitorDrivesChanged, ThreadOption.UIThread, false); 
I've tried a few different things now including:
var mockEvent = new Mock<MonitorDrivesEvent>();
mockEventAggregator.Setup(e => e.GetEvent<MonitorDrivesEvent>()).Returns(mockEvent.Object);
How should I be setting up the mock Event Aggregator to expect and deal with this call to .Subscribe()?

Any pointers would be great.

Thanks,
Apr 21, 2009 at 6:55 PM

Hi,

 

I wrote a small test for the event aggregator and I believe the problem is in this line:

      DriveInfoManager driveInfoManager = new DriveInfoManager(mockContainer as IUnityContainer, mockEventAggregator as IEventAggregator);

 

I tried this and was able to get it to work:

DriveInfoManager driveInfoManager = new DriveInfoManager(mockContainer.Object, mockEventAggregator.Object);

 

You will still need to execute this lines:

var mockEvent = new Mock<MonitorDrivesEvent>();
mockEventAggregator.Setup(e => e.GetEvent<MonitorDrivesEvent>()).Returns(mockEvent.Object);               

This will only work if DriveInfoManager only needs MonitorDrivesEvent event. If it requires anything else, you will need to mock it also.

 

Hope it helps!

 

Matias Bonaventura

http://blogs.southworks.net/matiasb