Missing Method Exception When Referencing .Net Sta

2019-04-25 09:10发布

I am getting the following exception when running a .Net 4.6.1 unit test that uses System.IO.Compression.ZipFile.Open, if the unit test project references a .Net Standard 2.0 assembly:

System.MissingMethodException: Method not found: 'System.IO.Compression.ZipArchive System.IO.Compression.ZipFile.Open(System.String, System.IO.Compression.ZipArchiveMode)'.
    at UnitTestProject.UnitTest1.TestMethod1()

The unit test project was created using the VS 2017 Unit Test project (not the .NET Core one) and references were added to System.IO.Compression.FileSystem and my standard class library:

using System.IO.Compression;
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace UnitTestProject
{
    [TestClass]
    public class UnitTest1
    {
        [TestMethod]
        public void TestMethod1()
        {
            string zipfilename = "C:\\temp\\out.zip";
            using (ZipArchive zipArchive = ZipFile.Open(zipfilename, ZipArchiveMode.Read)) { }
        }
    }

The .net standard class library is simply a single class with no methods:

namespace StandardClassLib
{
    public static class Zipper
    { // Class is empty.
    }
}

I get the same error using the Test Explorer in Visual Studio and from the command line using vstest.console.exe.

Note that this behavior only exhibits itself in a unit test project, Console Applications work fine.

Can anyone help me understand why this isn't working and a workaround to this issue (if possible)?

1条回答
2楼-- · 2019-04-25 09:46

This happens because the test project needs some additional binding redirects that need to be generated during the build process. While the project properties dialog has an option to auto-generate binding redirects, this has no effect for libraries (which classic unit test projects are) so you need to edit the .csproj file manually to include:

<PropertyGroup>
  <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
  <GenerateBindingRedirectsOutputType>true</GenerateBindingRedirectsOutputType>
</PropertyGroup>

For more details and explanations, see the announcement GitHub issue Issues with .NET Standard 2.0 with .NET Framework & NuGet and its linked discussion issue.

查看更多
登录 后发表回答