Mocking Prism Event Aggregator using Moq for Unit Testing
Asked Answered
G

1

6

I need some advice on how to use Moq in a unit test to make sure that my class under test is behaving how I want. That is the class under test publishes an Event Aggregator (from Prism) event and I need some way of asserting that this event has been raised in my test.

I don't have a lot of resource at work and am finding it difficult to know how to set this up.

I have :-

public SomeEvent : CompositePresentationEvent<SomeEvent>
{
   EventPayload
}

public SomeClass
{
     void Allocate(){EventAggregator.Publish<SomeEvent>}
}

public SomeService : IService
{
     SomeService(){ EventAggregator.Subscribe<SomeEvent>(DoSomething)}
     void DoSomething(SomeEvent evt){}
}

I think that if my test is for SomeClass I need to verify that if I call SomeClass.Allocate a SomeEvent message is being published. How is this done?

Do I also need to verify that a mocked SomeService is receiving the SomeEvent? Or is that a seperate unit test that belongs to SomeService unit test and not SomeClass?

In any event, not sure how to set any of this up so any advice would be appreciated.

Gushy answered 1/8, 2010 at 7:26 Comment(0)
J
11

You would supply SomeClass with an IEventAggregator, which will allow you to supply a mock during testing:

public SomeClass(IEventAggregator eventAggregator)
{
     _eventAggregator = eventAggregator;
}

Then your test would look something like this:

var fakeEventAggregator = new Mock<IEventAggregator>();
var fakeEvent = new Mock<SomeEvent>();

fakeEventAggregator.
    Setup(x => x.GetEvent<SomeEvent>()).
    Returns(fakeEvent.Object);

var test = new SomeClass(fakeEventAggregator.Object);
test.Allocate();

fakeEvent.Verify(x => x.Publish(It.IsAny<SomeEventArgs>()));

If these are unit tests then you would test the subscription entirely separately in the SomeService tests. You are testing that SomeClass correctly publishes an event and that SomeService behaves correctly when it is given an event to process.

Johnsen answered 12/9, 2010 at 9:58 Comment(2)
This example uses "Constructor Dependency Injection", since the dependency on IEventAggregator is injected during the SomeClass constructor.Index
Great answer, this helped me out a lot.Dehydrogenase

© 2022 - 2024 — McMap. All rights reserved.