我正在使用C#
应用程序,该应用程序使用Moq
进行测试。我试图计算一个方法被调用的次数。以下代码用于初始化测试对象:
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);
}
当使用RuleItem
实例化Rule
并且调试显示它被命中时,正在调用所讨论的方法。这是调用它的代码:
这是实际被调用的方法:
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);
}
这是我的测试:
[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!");
}
令人惊讶的是,如果它自己执行了测试,但如果测试与其他测试一起执行则会失败。例外情况如下:
测试方法Package.Views.RuleViewModelTest.Properties_Test扔了 异常:Moq.MockException:调用执行了1次但是 预计只有一次!模拟上的预期调用正好1 次,但是是0次:mock =&gt; mock.GetSearchInfoAsync(It.IsAny(), It.IsAny(),It.IsAny(), It.IsAny()) 没有配置设置。 没有进行调用。