【发布时间】:2016-11-06 08:40:44
【问题描述】:
我正在使用 TDD,并且想为 PubSubEvent 中可用的 Unsubscribe() 方法编写一个单元测试。因为没有接口,因为你继承自没有接口的父类,所以我不知道如何测试它。
我的服务和方法,我想测试一下:
public class FrameService: IFrameService
{
private readonly IEventAggregator _eventAggregator;
public void UnsubscribeEvents()
{
_eventAgregator.GetEvent<FrameAddedEvent>()
.Unsubscribe(FrameAddedEventHandler); // How to unit test this?
}
}
FrameAddedEvent 类,继承自 Prism 库的 PubSubEvent:
public class FrameAddedEvent: PubSubEvent<Frame>
{
}
Prism 库中的声明:
public class PubSubEvent<TPayload> : EventBase
{
public SubscriptionToken Subscribe(Action<TPayload> action);
}
我对代码行第一部分的测试(使用 MSTest 和 Moq)。 我现在需要另一个带有 Unsubscribe() 断言的 UnitTest
[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);
}
}
回答: 解释见下方评论,我只是为可能和我有同样问题的人添加代码。
伪类:
public class FakeFrameAddedEvent : FrameAddedEvent
{
public bool Unsubscribed { get; private set; }
public FakeFrameAddedEvent()
{
Unsubscribed = false;
}
public override void Unsubscribe(Action<Frame> subscriber)
{
Unsubscribed = true;
}
}
还有新的单元测试:
[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();
}
【问题讨论】:
标签: c# unit-testing tdd moq prism