棱镜 TDD 退订()

Prism TDD Unsubscribe()

我正在使用 TDD,并想为 PubSubEvent 中提供的 Unsubscribe() 方法编写单元测试。因为没有接口,因为你继承自父class,没有接口,所以我不知道如何测试它。

我的服务和方法,我想测试:

public class FrameService: IFrameService
{
     private readonly IEventAggregator _eventAggregator;

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

从 Prism 库的 PubSubEvent 继承的 FrameAddedEvent class:

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);
    }
}

答案: 请参阅下面的评论以获取解释,我只是为可能与我有相同问题的人添加代码。

假货class:

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();
    }

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

也就是说,您 可以 测试 EventAggregator 周围的东西,包括您自己的事件,例如参见 [​​=12=]。