In the previous post we touched on the fundamentals of using Moq, now we’ll delve a little deeper.
Please note, MOQ version 4.20 has introduced a SponsoreLink which appears to send data to some third party. See discussions on GitHub.
Verifications
So we can verify that a method or property has been called using the following
var mock = new Mock<IFeed>(); FeedViewModel vm = new FeedViewModel(mock.Object); vm.Update(); mock.Verify(f => f.Update());
This assumes that the vm.Update() calls the IFeed.Update().
But what if we are passing a mock into a view model and we want to verify a method on the mock is called but we don’t care about the specific arguments passed into the method. We can do the following (this example uses the IEventAggregator in Caliburn Micro)
var eventMock = new Mock<IEventAggregator>(); PostListViewModel vm = new PostListViewModel(eventMock.Object); eventMock.Verify(e => e.Subscribe(It.IsAny<PostListViewModel>()), Times.Once);
In the above example, PostListViewModel’s constructor is expected to call the Subscribe method on the IEventAggregator. The actual implementation passes this into the Subscribe method, but we’ll ignore the argument, except that we’re expecting it to be of type PostListViewModel. The It.IsAny