0

我正在努力编写一个测试,以确认我在 EventAggregator 关闭时正确取消订阅它。谁能指出(简单)答案?!

这是代码:

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

测试失败:

Moq.MockVerificationException:以下设置不匹配:IssuerSelectedEvent x => x.Unsubscribe(It.IsAny())

这是测试:

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

3 回答 3

2

在这里,我正在验证是否Unsubscribe在模拟对象上调用了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那么您将需要一个Setup用于Subscribe返回您在测试中创建的令牌的方法。

于 2011-10-08T00:11:37.120 回答
0

您需要告诉您的EventAggregator模拟返回您的模拟IssuerSelectedEvent

ea.Setup(x => x.GetEvent<IssuerSelectedEvent>()).Return(evnt.Object);
于 2011-10-06T16:42:03.020 回答
0

测试需要更改为:

[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);
    evnt.Setup(x => x.Unsubscribe(It.IsAny<SubscriptionToken>()));

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

    vm.Dispose();

    evnt.VerifyAll();
}
于 2011-10-07T08:29:16.970 回答