简体   繁体   中英

Missing Method Exception When Referencing .Net Standard Project From .Net 4.6.1 Unit Test

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

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.

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