从 .Net 4.6.1 单元测试引用 .Net 标准项目时缺少方法异常 [英] Missing Method Exception When Referencing .Net Standard Project From .Net 4.6.1 Unit Test
问题描述
我在运行使用 System.IO.Compression.ZipFile.Open
的 .Net 4.6.1 单元测试时遇到以下异常,如果单元测试项目引用了 .Net Standard 2.0 程序集:
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 问题 Issues with .NET Standard 2.0 with .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 标准项目时缺少方法异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!