Cedric Royer-Bertrand Cedric Royer-Bertrand - 1 year ago 101
C# Question

Prism TDD Unsubscribe()

I'm using TDD and want to write a unit test for the Unsubscribe() method available in with PubSubEvent. Because there is no interface as you inherit from the parent class, which has no interface, so I don't know how to test it.

My service and the method, I would like to test:

public class FrameService: IFrameService
{
private readonly IEventAggregator _eventAggregator;

public void UnsubscribeEvents()
{
_eventAgregator.GetEvent<FrameAddedEvent>()
.Unsubscribe(FrameAddedEventHandler); // How to unit test this?
}
}


The FrameAddedEvent class, that inherit from the PubSubEvent from Prism library:

public class FrameAddedEvent: PubSubEvent<Frame>
{
}


Declaration in Prism's library:

public class PubSubEvent<TPayload> : EventBase
{
public SubscriptionToken Subscribe(Action<TPayload> action);
}


My test (using MSTest and Moq) for the first part of the code line.
I need now another UnitTest with the assert on the Unsubscribe()

[TestClass]
public class FrameServiceTest
{
private Mock<IEventAgregator> _eventAgregator;

[TestMethod]
public void When_SubscribeEvents_Then_Get_FrameAddedEvent_From_EventAggregator()
{
var frameAddedEvent = new FrameAddedEvent();

_eventAgregator.Setup(x=>x.GetEvent<FrameAddedEvent>())
.Returns(frameAddedEvent);

_frameService.SubscribeEvents();

_serviceLayerEventAgregator.Verify(x => x.GetEvent<FrameAddedEvent>(), Times.Once);
}
}


ANSWER:
See comment below for the explanation, I'm just adding the code for people who might have the same problem as me.

The fake class:

public class FakeFrameAddedEvent : FrameAddedEvent
{
public bool Unsubscribed { get; private set; }

public FakeFrameAddedEvent()
{
Unsubscribed = false;
}

public override void Unsubscribe(Action<Frame> subscriber)
{
Unsubscribed = true;
}
}


And the new UnitTest:

[TestMethod]
public void When_UnsubscribeEvents_Then_Unsubscribe_Is_Call()
{
var frameAddedEvent = new FakeFrameAddedEvent();

_serviceLayerEventAgregator.Setup(x => x.GetEvent<FrameAddedEvent>())
.Returns(frameAddedEvent);

_frameService.UnsubscribeEvents();

Check.That(frameAddedEvent.Unsubscribed).IsTrue();
}

Answer Source

First of all, PubSubEvent is part of prism and that brings its own set of tests, so I doubt the necessity for you to write your own tests for that.

That being said, you can test stuff around the EventAggregator, including your own events, see this for example.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download