简体   繁体   中英

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):

T Get<T>();

I set up my mock 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? This seems like a straightforward case. The only wrinkle is that IGetUserQuery in turn inherits from a genericized type:

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.

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 .

Why are you trying to mock T Get<T> () in the first place? Interaction with the IoC container should be absolutely minimal, usually just at the toplevel "entry point" to your system.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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