验证用Moq调用的方法
本文关键字:方法 调用 Moq 验证 | 更新日期: 2023-09-27 18:08:46
试图验证一个方法正在模拟中被调用,但似乎无法弄清楚为什么我一直得到一个异常抛出,它没有被调用。所讨论的方法如下:
public class CustomerSyncEngine {
public CustomerSyncEngine(ILoggingProvider loggingProvider, ICrmProvider crmProvider, ICacheProvider cacheProvider) {
Logger = loggingProvider;
CrmProvider = crmProvider;
CacheProvider = cacheProvider;
}
public virtual void SyncPickLists() {
Logger.LogBeginPicklistSync();
// get all the pick lists from the local cache
var localCachePickLists = CacheProvider.GetPickLists().ToList();
// get all the pick lists from the remote system
var crmPickLists = CrmProvider.GetPickLists().ToList();
// build a sync plan
var changes = BuildPickListUpdatePlan(localCachePickLists, crmPickLists).ToList();
// run the sync
RunPickListSync(changes);
Logger.LogEndPicklistSync();
}
}
然后我写了这样一个测试:
[TestMethod]
public void TestSyncPickLists() {
// arrange
var mockCrm = new Mock<ICrmProvider>();
mockCrm.Verify(x => x.GetPickLists(), Times.Once(), "ICrmProvider.GetPickLists not called");
var mockCache = Mock.Of<ICacheProvider>();
var mockLogger = Mock.Of<ILoggingProvider>();
// act
var syncEngine = new CustomerSyncEngine(mockLogger, mockCrm.Object, mockCache);
syncEngine.SyncPickLists();
// assert
mockCrm.VerifyAll();
}
当我运行它时,测试失败,并显示我在Verify()中指定的消息。所以我设置了一堆断点,我看到测试从不调用syncEngine.SyncPickLists()方法,这让我感到困惑。所以我注释掉了两个Verify() &VerifyAll()语句,现在我看到正确调用的东西。我遗漏了什么?看起来我正在做的正是在快速入门以及这个线程中所显示的。
Tejs在原帖评论中的回答
你调用验证后调用SyncPickLists -这不是一个延迟的事情,因为它检查的值,然后在那里。移动调用SyncPickLists下面的行,就可以通过了。——tej