I'm trying to mock out IMemoryCache.Get
which I understand is an extention method. Moq
cannot override these and thus makes me mock the underlying methods that it calls. This is fine by me especially since that is the consensus on stack overflow. My problem comes when I try to mock out the underlying IMemoryCache.TryGetValue
. C# resolves this to the extension method version of this within Microsoft.Extensions.Caching.Abstractions
(TryGetValue<TItem>(this IMemoryCache cache, object key, out TItem value)
) which is defined under the same namespace and is a package included by the project that my test project is trying to test. The extension method is essentially "hiding" the underlying instance method. How do I mock out the plain interface method TryGetValue
given these constraints?
Asked
Active
Viewed 476 times
1

Ryan Clements
- 61
- 7
-
It doesn't work that way. Extension methods don't hide instance ones, in case of a clash, the normal methods win and the extensions must be called as regular static methods. See this one for more details: https://stackoverflow.com/q/13524372/2557263. It seems that it's also an extension method. – Alejandro Jul 21 '21 at 20:44
-
1I see what you mean. It turns out that the solution to my problem was to make sure the variable passed into the `out` parameter was typed as an `object` so that the type system would resolve to the instance method and not the extension method. – Ryan Clements Jul 21 '21 at 20:47
-
Isn't `IMemoryCache` **non-distributed**? Why would you want to mock out something that is merely using _local_ RAM? Now had the AUT been using `IDistributedCache` I would understand – Jul 21 '21 at 20:53
-
See if this helps https://stackoverflow.com/a/42387886/5233410 – Nkosi Jul 21 '21 at 21:43
-
@MickyD You bring up an excellent point that anyone reading should understand. It may not be necessary to mock out `IMemoryCachce` I did it because I felt it easier to mock out rather than figure out how to new up one from scratch. – Ryan Clements Jul 22 '21 at 16:04
-
@Nkosi ty for the link – Ryan Clements Jul 22 '21 at 16:04