【问题标题】:How can I create an instance of HttpConfiguration in a NUnit test using the new csproj format?如何使用新的 csproj 格式在 NUnit 测试中创建 HttpConfiguration 的实例?
【发布时间】:2020-07-18 13:55:08
【问题描述】:

我创建了一个单元测试(使用 NUnit),它创建了一个 HttpConfiguration 的实例,并且使用经典的 csproj 格式可以正常工作。测试成功。我还使用新的 csproj 格式创建了一个相同的单元测试(使用 xUnit)。这个测试也成功了。

到目前为止一切顺利。实际上,我想使用新的 csproj 格式创建一个 NUnit 测试。此测试因抛出 System.IO.FileLoadException 引用 Newtonsoft.Json, Version=6.0.0.0 而失败。

我觉得这很奇怪。在我所有的测试项目中,除了提到的单元测试框架之外,我还添加了两个包:Microsoft.AspNet.WebApi.Core 5.2.7Newtonsoft.Json 12.0.3 .

这是我测试失败的 csproj:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>net472</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNet.WebApi.Core" Version="5.2.7" />
    <PackageReference Include="Newtonsoft.Json" Version="12.0.3" />
    <PackageReference Include="NUnit" Version="3.2.0" />
  </ItemGroup>

</Project>

这是在旧项目格式中成功而在新项目格式中失败的单元测试。

[Test]
public void CreateInstance()
{
    var instance = new HttpConfiguration();
}

这是我的测试结果:

我真的很惊讶。我的测试使用旧的 csproj 格式使用 NUnit 成功。使用 xUnit 和新的 csproj 格式时,我的测试也成功了。因此,我使用哪种格式或框架并不重要。但是,当我将 NUnit 与新格式结合使用时,测试失败。这怎么可能,我怎样才能做到这一点? Newtonsoft.Json 的 12.0.3 版不是其他 2 个测试的阻碍,因此它也不应该适用于失败的测试。

我的代码也可以在on GitHub找到:

【问题讨论】:

标签: unit-testing nunit xunit csproj csproj-user


【解决方案1】:

您的 NUnit“OldStyle”项目引用了 Newtonsoft.Json 版本 6.0.4。这就是它工作的原因 - 此版本与 Microsoft.AspNet.WebApi.Core 一起安装,因此没有冲突。您的“NewStyle”项目引用了 Newtonsoft.Json 版本 12.0.3,并且与相同版本的 Microsoft.AspNet.WebApi.Core 存在冲突。

如果您在“OldStyle”项目中将 Newtonsoft.Json 升级到最新版本,它将在 app.config 中为您创建绑定重定向:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-12.0.0.0" newVersion="12.0.0.0" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
</configuration>

将此配置复制到您的“NewStyle”项目中,一切都会按预期工作。

【讨论】:

  • 我刚刚在最近的提交中做了更新。现在到处都在使用 Newtonsoft 12.03。情况保持不变。但是,将 app.config 复制到 NewStyle 会使单元测试成功。但是,我不应该需要它。 NewStyle.Xunit 项目在没有 app.config 的情况下成功。如果没有 app.config 文件,我不能让 NewStyle 成功吗?麻烦的是 NUnit,因为如果我选择另一个测试框架,完全没有问题。
  • 看起来 xunit 正在以某种方式自动生成它们。如果您不想使用 app.config,可以将:&lt;AutoGenerateBindingRedirects&gt;true&lt;/AutoGenerateBindingRedirects&gt; &lt;GenerateBindingRedirectsOutputType&gt;true&lt;/GenerateBindingRedirectsOutputType&gt; 添加到您的 .csproj。有了它们,NUnit 也可以正常工作。
  • 谢谢。这完全解决了我的问题。顺便说一句,将&lt;GenerateBindingRedirectsOutputType&gt;true&lt;/GenerateBindingRedirectsOutputType&gt; 添加到PropertyGroup 就可以了。
猜你喜欢
  • 2015-07-26
  • 2010-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多