C# Prism TDD取消订阅()
我正在使用TDD,并希望为with PubSubEvent中的Unsubscribe()方法编写一个单元测试。因为没有从父类继承的接口,而父类没有接口,所以我不知道如何测试它 我的服务和方法,我想测试:C# Prism TDD取消订阅(),c#,unit-testing,tdd,moq,prism,C#,Unit Testing,Tdd,Moq,Prism,我正在使用TDD,并希望为with PubSubEvent中的Unsubscribe()方法编写一个单元测试。因为没有从父类继承的接口,而父类没有接口,所以我不知道如何测试它 我的服务和方法,我想测试: public class FrameService: IFrameService { private readonly IEventAggregator _eventAggregator; public void UnsubscribeEvents() {
public class FrameService: IFrameService
{
private readonly IEventAggregator _eventAggregator;
public void UnsubscribeEvents()
{
_eventAgregator.GetEvent<FrameAddedEvent>()
.Unsubscribe(FrameAddedEventHandler); // How to unit test this?
}
}
公共类框架服务:IFrameService
{
私有只读ieventagegrator\u事件聚合器;
公共无效取消订阅事件()
{
_eventAgregator.GetEvent()
.Unsubscribe(FrameAddedEventHandler);//如何对此进行单元测试?
}
}
FrameAddedEvent类,从Prism库的PubSubEvent继承:
public class FrameAddedEvent: PubSubEvent<Frame>
{
}
public类FrameAddedEvent:PubSubEvent
{
}
Prism图书馆中的声明:
public class PubSubEvent<TPayload> : EventBase
{
public SubscriptionToken Subscribe(Action<TPayload> action);
}
公共类PubSubEvent:EventBase
{
公开订阅公开订阅(操作);
}
我的测试(使用MSTest和Moq)用于代码行的第一部分。
现在,我需要在Unsubscribe()上使用断言进行另一个单元测试
[TestClass]
公共类FrameServiceTest
{
私人模拟活动组织者;
[测试方法]
public void当订阅事件时,然后从事件聚合器()获取帧添加项
{
var frameAddedEvent=新frameAddedEvent();
_设置(x=>x.GetEvent())
.Returns(frameAddedEvent);
_frameService.SubscribeEvents();
_验证(x=>x.GetEvent(),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;
}
}
公共类fakeframeaddevent:frameaddevent
{
公共bool取消订阅{get;private set;}
公共伪造文件
{
取消订阅=错误;
}
公共覆盖无效取消订阅(操作订阅方)
{
取消订阅=真;
}
}
以及新的单元测试:
[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();
}
[TestMethod]
当_UnsubscribeEvents _然后_Unsubscribe _为_Call()时,公共无效
{
var frameAddedEvent=new fakeframeaddevent();
_servicelayereventagator.Setup(x=>x.GetEvent())
.Returns(frameAddedEvent);
_frameService.UnsubscribeEvents();
检查.That(frameAddedEvent.Unsubscribed).IsTrue();
}
首先,PubSubEvent
是prism的一部分,它有自己的测试集,所以我怀疑您是否有必要为此编写自己的测试
也就是说,您可以测试
事件聚合器
周围的内容,包括您自己的事件,例如参见。感谢您的回复,我知道这是一个prism功能。我不想测试Unsubscribe()方法本身,但请确保这是一个调用。这是确保代码正常运行的唯一方法。我使用了您在链接中给我的示例。我刚刚创建了一个假类。重写Unsubcribe()方法以设置bool,并在测试结束时检查bool是否具有正确的值。我将用代码编辑我的问题。
[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();
}