Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking Prism Event Aggregator using Moq for Unit Testing

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.

like image 419
LostInWPF Avatar asked Aug 01 '10 07:08

LostInWPF


1 Answers

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.

like image 101
GraemeF Avatar answered Oct 26 '22 23:10

GraemeF