将调用如何验证EventAggregator的unsubscri

将调用如何验证EventAggregator的unsubscri

本文介绍了使用Prism放置ViewModel时,将调用如何验证EventAggregator的unsubscribe方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力编写一个测试,以确认关闭了EventAggregator消息后,我正确地取消了订阅.任何人都可以指出(简单的)答案吗?!

I'm struggling to write a test that confirms that I am correctly unsubscribing from an EventAggregator's message when it is closed. Anyone able to point out the (simple) answer?!

这是代码:

public class ViewModel : BaseViewModel, IViewModel
{
    private readonly IEventAggregator eventAggregator;
    private SubscriptionToken token;
    IssuerSelectedEvent issuerSelectedEvent;

    public ViewModel(IView view, IEventAggregator eventAggregator)
    {
        this.eventAggregator = eventAggregator;
        View = view;

        issuerSelectedEvent = eventAggregator.GetEvent<IssuerSelectedEvent>();
        token = issuerSelectedEvent.Subscribe(SelectedIssuerChanged, true);
    }

    private void SelectedIssuerChanged(IssuerSelectedCommand obj)
    {
        Console.WriteLine(obj);
    }

    public IView View { get; set; }

    public override void Dispose()
    {
        issuerSelectedEvent.Unsubscribe(token);
    }
}

测试失败,并显示以下信息:

The test fails with:

这是测试:

[Test]
public void UnsubscribeFromEventAggregatorOnDispose()
{
    var view = new Mock<ICdsView>();
    var ea = new Mock<EventAggregator>();
    var evnt = new Mock<IssuerSelectedEvent>();

    evnt.Setup(x => x.Unsubscribe(It.IsAny<SubscriptionToken>()));

    var vm = new CdsIssuerScreenViewModel(view.Object, ea.Object);

    vm.Dispose();

    evnt.VerifyAll();
}

推荐答案

在这里,我正在验证是否在模拟的IssuerSelectedEvent

Here I am verifying that the Unsubscribe was called on the mocked IssuerSelectedEvent

[Test]
public void UnsubscribeFromEventAggregatorOnDispose()
{
    var view = new Mock<ICdsView>();
    var ea = new Mock<IEventAggregator>();
    var evnt = new Mock<IssuerSelectedEvent>();

    ea.Setup(x => x.GetEvent<IssuerSelectedEvent>()).Returns(evnt.Object);

    var vm = new CdsIssuerScreenViewModel(view.Object, ea.Object);

    vm.Dispose();

    evnt.Verify(x => x.Unsubscribe(It.IsAny<SubscriptionToken>());
}

如果要检查是否将完全相同的令牌传递到Unsubscribe中,则对于Subscribe方法,您将需要Setup,该方法将返回您在测试中创建的令牌.

If you want to check that the exact same token is passed into the Unsubscribe then you will need a Setup for the Subscribe method that returns a token you create in your test.

这篇关于使用Prism放置ViewModel时,将调用如何验证EventAggregator的unsubscribe方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-22 10:55