我正在努力编写一个测试,确认我在关闭时正确取消了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 =&gt; 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();
}
答案 0 :(得分: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
,以返回您在测试中创建的令牌。
答案 1 :(得分:0)
您需要告诉EventAggregator
模拟器返回您的模拟IssuerSelectedEvent
:
ea.Setup(x => x.GetEvent<IssuerSelectedEvent>()).Return(evnt.Object);
答案 2 :(得分: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();
}