I’m using the Composite Application Library‘s event aggregator, and would like to create a mock for the IEventAggregator interface, for use in my unit test.
I’m planning on using Moq for this task, and an example test so far looks something like this:
var mockEventAggregator = new Mock<IEventAggregator>(); var mockImportantEvent = new Mock<ImportantEvent>(); mockEventAggregator.Setup(e => e.GetEvent<SomeOtherEvent>()).Returns(new Mock<SomeOtherEvent>().Object); mockEventAggregator.Setup(e => e.GetEvent<SomeThirdEvent>()).Returns(new Mock<SomeThirdEvent>().Object); // ... mockEventAggregator.Setup(e => e.GetEvent<ImportantEvent>()).Returns(mockImportantEvent.Object); mockImportantEvent.Setup(e => e.Publish(It.IsAny<ImportantEventArgs>())); // ...Actual test... mockImportantEvent.VerifyAll();
This works fine, but I would like know, if there is some clever way to avoid having to define an empty mock for every event-type my code might encounter (SomeOtherEvent, SomeThirdEvent, …)? I could of course define all my events this way in a [TestInitialize] method, but I would like to know if there is a more clever way? 🙂
I found the solution for this one:
will make the mockEventAggregator return mocks for all nested objects.