[英]Using Moq for Generic methods
Totally simple situation, but I can't make it work.完全简单的情况,但我不能让它工作。 I am running into an issue with using Moq to mock a generic method (in this case, on a Ninject Kernel interface):
我遇到了使用 Moq 模拟通用方法的问题(在本例中,在 Ninject Kernel 接口上):
T Get<T>();
I set up my mock object:我设置了我的模拟 object:
Mock<IKernel> mockKernel = new Mock<IKernel>();
mockKernel.Setup(x => x.Get<IGetUserQuery>()).Returns(new GetUserQuery());
At runtime I get the following exception:在运行时,我得到以下异常:
Expression references a method that does not belong to the mocked object: x => x.Get<IGetUserQuery>(new[] { })
Any idea why it's throwing this?知道为什么要扔这个吗? I've mocked generics in Moq before without a problem... are there cases in which generic mocking isn't supported?
我之前在 Moq 中模拟了 generics 没有问题......是否存在不支持通用 mocking 的情况? This seems like a straightforward case.
这似乎是一个简单的案例。 The only wrinkle is that IGetUserQuery in turn inherits from a genericized type:
唯一的问题是 IGetUserQuery 又继承自一个泛型类型:
IGetUserQuery : ICommand<UserQueryInput, UserQueryOutput>
I don't see this creating a problem because the generic types for this implementation of ICommand are staticly defined by IGetUserQuery, so I doubt this is confusing Moq.我不认为这会造成问题,因为 ICommand 的这个实现的泛型类型是由 IGetUserQuery 静态定义的,所以我怀疑这会混淆 Moq。
Thanks in advance提前致谢
The problem is that T Get<T> ()
isn't actually a method defined in the IKernel interface, it is an extension method defined here .问题是
T Get<T> ()
实际上不是 IKernel 接口中定义的方法,它是此处定义的扩展方法。
Why are you trying to mock T Get<T> ()
in the first place?你为什么要首先模拟
T Get<T> ()
? Interaction with the IoC container should be absolutely minimal, usually just at the toplevel "entry point" to your system.与 IoC 容器的交互应该是绝对最小的,通常只是在系统的顶层“入口点”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.