如果使用设置,Moq 模拟调用返回 null

Vla*_*zki 5 c# unit-testing moq mocking

我正在使用 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());
Run Code Online (Sandbox Code Playgroud)

我想测试一次呼叫是否只进行了一次。我正在尝试这样:

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!");
}
Run Code Online (Sandbox Code Playgroud)

这是它实际被调用的方法:

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);
}
Run Code Online (Sandbox Code Playgroud)

问题是,如果我使用上面详述的这一行,

_serviceMock.Setup(mock => mock.GetSearchInfoAsync(It.IsAny<CancellationToken>(), It.IsAny<IEnumerable<string>>(), It.IsAny<identifierType>(), It.IsAny<bool>())).Callback(() => _count++);
Run Code Online (Sandbox Code Playgroud)

这将返回 null 并生成 NullPointerException:

Service.GetSearchInfoAsync(cancellationToken, new[] {queryValue}, identifierType)
Run Code Online (Sandbox Code Playgroud)

但是,如果我注释掉该行,则测试运行良好(尽管不计算调用次数)。

我究竟做错了什么?这是我第一次为此使用 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());
Run Code Online (Sandbox Code Playgroud)

Chr*_*air 4

当您“设置”该方法时,您设置了回调,但不提供返回值。因此,当调用模拟方法时,它将返回返回类型的默认值(在这种情况下,类型Task<>将产生null返回值)。因此,当您的Search方法调用您的模拟GetSearchInfoAsync方法时,它会收到一个null引用,当它稍后尝试调用时,该引用自然会失败.ContinueWith它时,该引用自然会失败。

尝试添加一个为您的模拟方法.Returns()提供虚拟数据的函数Task<>

_serviceMock.Setup(mock => mock.GetSearchInfoAsync(It.IsAny<CancellationToken>(), It.IsAny<IEnumerable<string>>(), It.IsAny<identifierType>(), It.IsAny<bool>()))
    .Returns(new Task<IEnumerable<ISearchResult>>(Enumerable.Empty<ISearchResult>))
    .Callback(() => _count++);
Run Code Online (Sandbox Code Playgroud)