简体   繁体   English

MOQ验证无效

[英]MOQ verify not working on void

I have an odd problem when using moq. 使用moq时我有一个奇怪的问题。

In one project when I try to verify that a method has been called it says it has not. 在一个项目中,当我尝试验证方法已被调用时,它说它没有。 When I debug the test it clearly calls the method. 当我调试测试时,它清楚地调用该方法。

It's a simple cache object where I want to see if I add something to the cache. 这是一个简单的缓存对象,我想看看我是否在缓存中添加了一些东西。 I have (among others) Add, Contains and Get methods. 我有(以及其他)Add,Contains和Get方法。

My verify works fine on these methods: 我的验证在这些方法上运行良好:

bool Contains(string key);
T Get<T>(string key);

But not on this: 但不是这个:

void Add(string key, object objectToCache, CacheItemPolicy policy);

I have tried whit the exact values I give to the method as this: 我已经尝试了我给方法的确切值,如下所示:

mockedCache.Verify(p => p.Add(LOCATION_CACHE_KEY, locations, policy), Times.Once());

Using It.IsAny 使用It.IsAny

mockedCache.Verify(p => p.Add(It.IsAny<string>(), It.IsAny<IEnumerable<string>>(),
     It.IsAny<CacheItemPolicy>()), Times.Once());

And no matter what I try I get the response that it was called 0 times. 无论我尝试什么,我得到它被称为0次的响应。

I have never seen this behaviour before. 我以前从未见过这种行为。 Can anybody tell me what is wrong? 谁能告诉我有什么问题?

Thanks 谢谢

Michael 迈克尔

Update: As @SergRogovtsev suggested, I looked at the output moq generated. 更新:正如@SergRogovtsev建议的那样,我查看了生成的输出moq。

My method whas not called with IEnumerable but with List 我的方法没有用IEnumerable调用,而是用List调用

As you've seen, Moq is not checking the exact types of the parameters passed, not just that they derive from the type you are asserting. 正如您所见,Moq不会检查传递的参数的确切类型,而不仅仅是它们来自您声明的类型。 If you want that functionality you may need to use something like this: 如果你想要这个功能,你可能需要使用这样的东西:

mockedCache.Verify(p => p.Add(It.IsAny<string>(), It.Is<object>(o => o is IEnumerable<string>), It.IsAny<CacheItemPolicy>()), Times.Once());

Otherwise you could look into getting an updated version of Moq - I have tested your original scenario (using It.IsAny<IEnumerable<string>> in the assertion) and it works correctly with Moq v4.0) 否则你可以考虑获得Moq的更新版本 - 我测试了你的原始场景(在断言中使用It.IsAny<IEnumerable<string>> )并且它与Moq v4.0一起正常工作)

Does CacheItemPolicy implements an interface? CacheItemPolicy是否实现了接口? If so, will you try verifying the call with 如果是这样,您会尝试验证通话吗?

mockedCache.Verify(p => p.Add(It.IsAny<string>(), It.IsAny<IEnumerable<string>>(), It.IsAny<ICacheItemPolicy>()), Times.Once());

or whatever the interface's name is? 或者界面名称是什么?

I had the same problem. 我有同样的问题。 Thing is, my SUT method received an interface, and that's what it passed to the mocked object. 事实上,我的SUT方法收到了一个接口,这就是它传递给模拟对象的内容。 Though the class may implement the interface, the interface is still a different type. 虽然该类可以实现接口,但接口仍然是不同的类型。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM