Moq Verify number of calls works if test called alone, but not if called along other tests

半腔热情 提交于 2020-01-07 02:56:07

问题


I am working on a C# application, which uses Moq for testing. I am trying to count the number of times a method is being called. The following piece of code is used to initialise the test objects:

private Mock<IService> _serviceMock;

[TestInitialize]
public void Initialize()
{
    MockServices();

    Rule rule = new Rule(
        // Parameters
        );

    RuleItem = new RuleItem(rule);
}

private void MockServices()
{
    UnityContainer unityContainer = new UnityContainer();

    _serviceMock = new Mock<IService>();
    unityContainer.RegisterInstance(typeof (IService), _serviceMock.Object, new ContainerControlledLifetimeManager());

    UnityServiceLocator locator = new UnityServiceLocator(unityContainer);
    ServiceLocator.SetLocatorProvider(() => locator);
}

The method in question is being called when the RuleItem is being instantiated with a Rule and debugging shows that it is being hit. This is the code where it gets called:

This is the method where it actually gets called:

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 =>
            {
                // Debugging shows that it reaches in here on each test.
            }, CancellationToken.None, TaskContinuationOptions.None, TaskScheduler.Default);
}

This is my test:

[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 not performed only once!");
}

The surprising thing is that the test passes if it's executed by itself but it fails if it is executed together with other tests. The exception is as follows:

Test method Package.Views.RuleViewModelTest.Properties_Test threw exception: Moq.MockException: Invocation was performed 1 times but was expected only once! Expected invocation on the mock exactly 1 times, but was 0 times: mock => mock.GetSearchInfoAsync(It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()) No setups configured. No invocations performed.

来源:https://stackoverflow.com/questions/34205261/moq-verify-number-of-calls-works-if-test-called-alone-but-not-if-called-along-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!