本文介绍了从.Net 4.6.1单元测试中引用.Net标准项目时,缺少方法异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果单元测试项目引用的是.Net Standard 2.0程序集,则在运行使用System.IO.Compression.ZipFile.Open的.Net 4.6.1单元测试时出现以下异常:

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

使用VS 2017单元测试项目(不是.NET Core之一)创建了单元测试项目,并将引用添加到System.IO.Compression.FileSystem和我的标准类库中:

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)) { }
        }
    }

.net标准类库只是一个没有方法的单个类:

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

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

在Visual Studio中使用测试资源管理器",以及在命令行中使用"vstest.console.exe",我遇到相同的错误.

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

推荐答案

之所以会发生这种情况,是因为测试项目需要一些额外的绑定重定向,这些重定向需要在构建过程中生成.尽管项目属性对话框具有自动生成绑定重定向的选项,但这对库没有影响(经典的单元测试项目是库),因此您需要手动编辑.csproj文件以包括:

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>

有关更多详细信息和解释,请参阅GitHub问题公告有关.NET Standard 2.0和.NET的问题框架与NuGet 及其相关的讨论问题.

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.

这篇关于从.Net 4.6.1单元测试中引用.Net标准项目时,缺少方法异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 11:48