MissingMethodException / "Method not found" after update to Moq 4.8.0
Hi,
Today I've tried updating the NuGet package from 4.7.145.0 to 4.8.0.0 and I'm running into an issue with a specific test case failing now on a strange error message. To give you some context, in our tests we create a HttpActionContext to test our authentication. This is native .net functionality. I've isolated the issue to the following code:
[Test]
public void OnActionExecuting_ShouldFillMarketInSession() {
var fakeActionContext = _CreateFakeHttpActionContext();
}
private HttpActionContext _CreateFakeHttpActionContext() {
return new HttpActionContext(null, new ReflectedHttpActionDescriptor()) {
Response = new HttpResponseMessage(HttpStatusCode.OK)
};
}
When running this test, it fails with the following error:
System.MissingMethodException : Method not found: 'Void System.Web.Http.Controllers.HttpActionContext.set_Response(System.Net.Http.HttpResponseMessage)'. at SMP.Api.Test.Filter.MoqTest._CreateFakeHttpActionContext() at SMP.Api.Test.Filter.MoqTest.OnActionExecuting_ShouldFillMarketInSession() in C:\Projects\Athena\Athena\SMP.Api.Test\Filter\MoqTest.cs:line 14
Could you help me figure out what is wrong, or fix this if it is an actual bug?
Thanks, John
Hi @JHotterbeekxBannerconnect and thanks for reporting. Unfortunately, I do not see anything related to Moq in your example code, so I have to wonder whether your issue is even related to Moq at all.
Could you please provide a short but complete code example that demonstrates this issue, and shows how Moq is involved? (Otherwise I'll close this issue in a couple of days' time.) Thank you!
(Btw. MissingMethodExceptions usually indicate that you have old DLLs lurking around somewhere that are not binary-compatible with the version against which your code was compiled. Try deleting your project's obj and bin folders, your test runner's cache (if applicable), and possibly also your project's or user profile's NuGet package cache.)
Hi, I think I'm seeing the same problem. Out of 405 tests using Moq, 16 started failing after upgrading to Moq 4.8.0 with exception "System.MissingMethodException: Method not found". It seems to be related to the "System.Net.Http" namespace since all the "missing methods" in the failing tests have types from that namespace in their signature (eg. "System.Net.Http.HttpResponseMessage").
@JHotterbeekxBannerconnect, @willykc: Could it be that you updated not just Moq, but any other Microsoft ASP.NET packages at the same time without noticing it? Because quite frankly, Moq has no dependency on, nor any special logic related to, any System.Net.Http.* types. I don't see how this issue could be caused by Moq, especially when the MissingMethodException gets triggered in a piece of code that doesn't even involve Moq.
We've updated several packages, but saw tests failing. So I reverted everything and updated one by one, everything keeps working until the last package is updated, which is Moq. But I'm going to try cleaning old DLL's and cache and see what that does, and if it still doesn't work try a new solution to reproduce this.
@JHotterbeekxBannerconnect: That's truly strange. Until you have repro code ready to share, could you perhaps give the following information:
- What version of Visual Studio are you working with?
- What exact framework / platform are your projects targeting?
- What NuGet packages (including version numbers) are your projects referencing?
- Are you using
<PackageReference>s or a NuGetpackages.config? - Are there any assembly binding redirects in your App.config or Web.config? If so, what do they look like?
- Is there a
<AutoGenerateBindingRedirects>element in your root project file? If so, what is its value?
@stakx I've been able to reproduce it in a simple test project: Working.without.Moq.zip
When you open this (in VS 2017) you'll see that there is one single test in there. This runs without any issues. Now try adding through NuGet, you'll see that the test fails.
I've found something more interesting, when updating to the latest version of Moq through NuGet, another package seems to come along called System.Threading.Tasks.Extensions.4.4.0. This is the one that seems to be causing the error, because if I remove this as reference from the included test project, the test will succeed again.
The other info you requested (for the test solution):
- VS 2017 Professional 15.5.2 / .net v 4.7.02556
- Any CPI
- Just Moq 4.8.0
- packages.config
- None
Hopefully this is enough for you to reproduce it.
Thanks a lot for the test solution, and the analysis you've done already! I can now reproduce this issue.
(One problem I noticed before I could even run your tests is that your project is a missing System.Web.Http assembly. I've resolved this one by installing the Microsoft.AspNet.WebApi.Core package.)
I'll now try to find the precise cause of this.
OK, seems you're affected by the problem described in https://github.com/dotnet/standard/issues/481, and adding the following to your MoqTests.csproj file appears to resolve the issue:
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
(PS: Alternatively, update your project file(s) to the new SDK format, which should already implicitly include the above properties.)
The problem indeed gets triggered by System.Threading.Tasks.Extensions package (which Moq references because of ValueTask<TResult>). Note that it does not target the full .NET Framework, only .NET Standard. Referencing a .NET Standard assembly from a .NET Framework project used to not work, but support for doing just that was added in .NET 4.6.1. Unfortunately, it's a pretty flaky feature and it sometimes requires assembly binding redirects (which your test project doesn't have).
Please see the issue referenced above for details.
@stakx Thanks a lot for the help and explanation! I've added the properties to the solution and the tests run without any issue now. Seems like something that more people could run into, maybe this should be put in the wiki somewhere?
@JHotterbeekxBannerconnect - I agree that this situation needs to be improved. I'm currently looking into Moq's reference of the System.Threading.Tasks.Extensions package (which was added in 2194e5fe). It doesn't seem right that this package is referenced at all by the net45 target, as this framework version didn't yet allow references to .NET Standard assemblies. And then there's that issue I linked to to deal with.
Adding a warning to the wiki would be a start... would you like to do this?
Short of temporarily removing ValueTask<TResult> support in Moq for the full .NET Framework, I'm not sure how to cleanly resolve this problem. @AdamDotNet — you added the package reference to System.Threading.Tasks.Extensions to Moq a while ago. Do you by chance know how to properly deal with this kind of problem (cross-target assembly references)?
I'm also still not sure yet why just referencing that assembly caused the issue (note that your test doesn't make use of it).
@stakx I've added it as a FAQ to the wiki, referencing to the .net standard issue and this issue. Great that you'll look in to this, I agree that it feels weird that this issue is being caused, and even stranger without actually using anything from the reference.
Hi @stakx, thanks a lot for the solution. After adding the property group to my test project file, all the failing tests are now passing.
I'm not sure if this could help but an idea would be to add a .props file including the property group to the Moq NuGet package like so: https://docs.microsoft.com/en-us/nuget/create-packages/creating-a-package#including-msbuild-props-and-targets-in-a-package
@stakx It seems that the adding of a .net standard reference was also causing issues on our TeamCity servers, which we had to resolve as well by updating the build tools and adding .net Core support. Just telling you because this could become an issue for more people.
@JHotterbeekxBannerconnect, thanks a lot for setting up the FAQ! It's great to have such a resource that we can direct people to. :+1:
@willykc, that's good to know—thanks for the link. However, I don't feel too comfortable about Moq influencing the build process behind the user's back. Moq is just a library and just one out of many possible dependencies a project might have. Imagine the potential complications if every dependency secretly modified your build. Some people might not actually want to have assembly binding redirects generated automatically.
I believe the problem should be solved at the source, if possible. And I suspect it's that the build process picks the wrong assembly version from the System.Threading.Tasks.Extensions package (starting with .NET 4.6.1, it can pick either the .NET Standard assembly, or the Portable Class Library assembly, the latter of which is probably the right one to pick). I'll try to figure out the exact circumstances under which this problem appears.
If all else fails, I'm quite ready to temporarily remove ValueTask<TResult> support from Moq so people don't run into this while we find a permanent solution.
I'll keep you updated!
@stakx My understanding is that, it's not .Net 4.6.1 that enabled referencing .Net Standard libraries, it's that .Net 4.6.1 was the lowest version that works with .Net Standard 2.0 specifically. The tooling (VS) helps you reference .Net Standard libraries, not necessarily the Framework you are targeting.
The System.Threading.Tasks.Extensions NuGet has a dependency on .Net Standard 1.0, the lowest common denominator. Microsoft's documentation on .Net Standard states that a 1.0 library is compatible with .Net Framework 4.5. Therefore, it shouldn't be a problem to have the net45 TFM reference the System.Threading.Tasks.Extensions NuGet. Visual Studio / NuGet.exe should pick up the "most correct" version of the NuGet when multiple targets are available.
However, it is possible to only reference the NuGet on a specific TFM, and then #if out the relevant code if that's what you want. In fact, the Moq CSProj already does that.
For what it's worth, I just tried the following sample code on a .Net 4.5 console app without any compilation, or runtime issues; using VS 2017 15.5.2.
using Moq;
using System;
using System.Threading.Tasks;
namespace ConsoleApp1
{
public interface IFoo
{
ValueTask<string> Bar();
}
class Program
{
static async Task Main(string[] args)
{
Mock<IFoo> mock = new Mock<IFoo>();
mock.Setup(m => m.Bar()).ReturnsAsync("Hello world");
string bar = await mock.Object.Bar();
Console.WriteLine(bar);
}
}
}
Does this answer your questions?
PS. I definitely have felt the pain of .Net Standard in .Net Framework :(
Let me summarize my findings regarding MissingMethodExceptions in Moq 4.8.0. Below, you'll find:
- a very minimal test project which reproduces the issue;
- an explanation of what exactly triggers it; and
- a description of how to resolve this issue.
(I originally wanted to include a rant about .NET Core, .NET Standard, and NuGet having put us back firmly in DLL hell, and about the continually sorry state of .NET tooling surrounding those three; but anyone working with .NET who hasn't lived under a rock in the past few years probably knows that already, so I've edited it out. 😜)
1. Test project that reproduces a MissingMethodException:
Download it here: MinimalRepro.zip (1.4 KB).

Please note:
- Does not reference Moq. Because Moq isn't actually to blame. :sunglasses:
- There is a warning about an assembly version conflict, and a hint about adding a
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>property to the project file. Depending on the way how you set up your own projects, you might or might not see something similar.
2. Why is the MissingMethodException occurring?
- The test project targets the full .NET Framework (4.6.1, but the exact version is perhaps unimportant).
- We are referencing the
System.Threading.Tasks.ExtensionsNuGet package, presumably because we'd like to useValueTask<>somewhere in our project. - That package does not explicitly have an assembly for that target. Among other targets, it supports Portable Class Library profile 259 (which includes .NET 4.5) and .NET Standard 1.0. Visual Studio / MSBuild will pick the latter.
- Referencing a .NET Standard assembly (
System.Threading.Tasks.Extensions) from a .NET Framework project (MinimalRepro) implies that during a build, a whole lot of supporting .NET Standard assemblies will be copied to the output directory—regardless of whether we actually use the .NET Standard library or not. Because of that copying, ourMinimalRepro's output directory will now have a .NET StandardSystem.Net.Httpassembly, version 4.2.0.0. - The
Microsoft.AspNet.WebApi.CoreNuGet package however references the target framework'sSystem.Net.Httpversion 4.0.0.0 (against which it was compiled). - Our own code references stuff from both
System.Net.Httpversion 4.2.0.0 (HttpResponseMessage) and fromMicrosoft.AspNet.WebApi.Core(HttpActionContext). - Thus both versions 4.0.0.0 and 4.2.0.0 are referenced and we have a version conflict which will eventually surface as the
MissingMethodException.
My personal conclusion is that System.Net.Http or some of the ASP.NET assemblies are versioned incorrectly. https://github.com/aspnet/Hosting/issues/926#issuecomment-276674380 hints at the same thing ("...some of the ongoing issues with the System.Net.Http packages...").
3. How can I resolve this problem?
As mentioned above, try adding this to your .csproj or .vbproj project file:
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>
(This shouldn't be necessary if you're using the new SDK project file format, so you can also just convert to that instead.)
And finally... 🥁
4. What can be done at Moq's end?
-
What I would like to do first is... nothing, for these reasons:
- I'd like to see how many people actually run into this problem.
- I'd like to see whether this problem occurs mostly within the context of ASP.NET. This would indicate that the ASP.NET folks version their assemblies incorrectly. If, however, the problem happens in a lot of different scenarios, then the tooling would be to blame.
-
l'll direct the first few people at the FAQ set up by @JHotterbeekxBannerconnect.
-
Beyond that, if more complaints keep rolling in, I might remove support for
ValueTask<>andValueTuple<>from Moq'snet45target. It's pretty much the only possible fix until enough time has passed for people to upgrade their tools and projects to a working combination of NuGet / MSBuild / VS.
I am open to suggestions how to resolve this in a better way.
@stakx - I think for now your suggestion of wait and see a little longer probably best. The "holy grail" of .Net Standard sounded really cool until it all fell apart in actual use (in .Net Framework). System.Net.Http is probably the biggest offender, as you've found out. I can't find the war story that came to mind, but it was bad...
A possible solution is to create a Moq.Extensions NuGet. Then treats like ValueTask
@AdamDotNet, thanks for this feedback, it's much appreciated. Wait a little longer it is, then!
A possible solution is to create a Moq.Extensions NuGet. Then treats like ValueTask can be opt in rather than everyone just gets it.
This is a pretty good idea! We just might do that if things don't get better soon. Thank you for suggesting it! (And, if you'd like to contribute by moving the offending bits into a separate package via a PR, please just let me know. I could signal you when the time's right.)
@stakx - I could probably find time to create a new project in the Moq solution and move things over (a list of exactly what you want moved over would be appreciated, if more than just ValueTask). I'm not familiar with how you configure the build server script though.