问题
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?!
Here is the code:
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:
Moq.MockVerificationException : The following setups were not matched: IssuerSelectedEvent x => x.Unsubscribe(It.IsAny())
Here is the test:
[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();
}
回答1:
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>());
}
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.
回答2:
You need to tell your EventAggregator
mock to return your mocked IssuerSelectedEvent
:
ea.Setup(x => x.GetEvent<IssuerSelectedEvent>()).Return(evnt.Object);
回答3:
The tests needs to be changed to:
[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();
}
来源:https://stackoverflow.com/questions/7675520/how-to-verify-the-eventaggregators-unsubscribe-method-is-called-when-disposing