我正在使用Moq为C#应用编写测试。我的测试初始化器包含以下代码:
UnityContainer unityContainer = new UnityContainer();
_serviceMock = new Mock<IService>();
_serviceMock.Setup(mock => mock.GetSearchInfoAsync(It.IsAny<CancellationToken>(), It.IsAny<IEnumerable<string>>(), It.IsAny<identifierType>(), It.IsAny<bool>())).Callback(() => _count++);
unityContainer.RegisterInstance(typeof(IService), _serviceMock.Object, new ContainerControlledLifetimeManager());
我希望测试只调用一次的函数。我尝试以下方式:
int _count = 0;
[TestMethod]
public void Properties_Test()
{
_serviceMock.Verify(mock => mock.GetSearchInfoAsync(It.IsAny<CancellationToken>(), It.IsAny<IEnumerable<string>>(), It.IsAny<identifierType>(), It.IsAny<bool>()), Times.Exactly(1), "Invocation was performed " + _count + " times but was expected only once!");
}
这是实际调用该方法的方式:
private void Search(string queryValue, identifierType identifierType)
{
CancellationToken cancellationToken;
lock (_syncLock)
{
_cancellationTokenSource.Cancel();
_cancellationTokenSource = new CancellationTokenSource();
cancellationToken = _cancellationTokenSource.Token;
}
IService Service = ServiceLocator.Current.GetInstance<IService>();
Service.GetSearchInfoAsync(cancellationToken, new[] {queryValue}, identifierType)
.ContinueWith(
task =>
{
// Do stuff
}, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}
问题在于,如果我按照上述详细说明使用此行代码,
_serviceMock.Setup(mock => mock.GetSearchInfoAsync(It.IsAny<CancellationToken>(), It.IsAny<IEnumerable<string>>(), It.IsAny<identifierType>(), It.IsAny<bool>())).Callback(() => _count++);
这个返回null并且导致NullPointerException异常:
Service.GetSearchInfoAsync(cancellationToken, new[] {queryValue}, identifierType)
然而,如果我注释掉那一行,测试就可以正常运行(尽管不能计算调用次数)。
我做错了什么?这是我第一次使用 Moq,就我所知,我已经正确实现了计数功能。
编辑:根据 Chris Sinclair 的建议,我已将初始化程序更改为以下内容,这解决了问题:
UnityContainer unityContainer = new UnityContainer();
_serviceMock = new Mock<IService>();
Task<IEnumerable<ISearchResult>> task = new Task<IEnumerable<ISearchResult>>(Enumerable.Empty<ISearchResult>);
_serviceMock.Setup(mock => mock.GetSearchInfoAsync(It.IsAny<CancellationToken>(), It.IsAny<IEnumerable<string>>(), It.IsAny<identifierType>(), It.IsAny<bool>())).Returns(task).Callback(() => _count++);
unityContainer.RegisterInstance(typeof(IService), _serviceMock.Object, new ContainerControlledLifetimeManager());