【问题标题】:Prism TDD Unsubscribe()棱镜 TDD 取消订阅()
【发布时间】: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


    【解决方案1】:

    首先,PubSubEvent 是 prism 的一部分,它带来了自己的一组测试,所以我怀疑你是否有必要为此编写自己的测试。

    话虽如此,您可以测试 EventAggregator 周围的东西,包括您自己的事件,例如参见 this

    【讨论】:

    • 感谢您的回复,我知道这是棱镜功能。我不想测试 Unsubscribe() 方法本身,但请确保这是调用。这是确保代码正常运行的唯一方法。
    • 我使用了你在链接中给我的例子。我刚刚创建了一个假课程。覆盖 Unsubcribe() 方法以设置一个 bool 并在测试结束时检查该 bool 是否具有正确的值。我将使用代码编辑我的问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-19
    • 2017-12-18
    • 2012-03-14
    • 2016-07-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多