新的 HttpConfiguration(); Nunit 失败但 MsTests 失败

new HttpConfiguration(); fails with Nunit but not MsTests

我正在尝试使用 Nunit 创建一个测试项目来测试我的 Webapi 1 路由。问题是我总是遇到这个异常:

An exception of type 'System.IO.FileNotFoundException' occurred in System.Net.Http.Formatting.dll but was not handled in user code

Additional information: Could not load file or assembly 'Newtonsoft.Json, Version=4.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dependencies. The system cannot find the file specified.

我已经尝试 运行 使用 MsTests(一个新的 testProject)编写代码,但没有出现异常。

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Http;
using NUnit.Framework;


namespace UnitTestProject1
{
    [TestFixture]
    [TestClass]
    public class UnitTest1
    {
        [Test]
        [TestMethod]
        public void TestMethod1()
        {
            var config = new HttpConfiguration();
        }
    }
}

所以在那个例子中我可以 运行 MsTest 和 Nunit。 MsTest 工作正常,但 Nunit 不行。有谁知道为什么? 我也试过 Gallio + MBUnit 但它不起作用。

更多信息: 框架目标:.net 4.0 System.Web.Http 版本 4.0.0

只需添加对 Newtonsoft.json 的引用,然后在 app.config/web.config 中添加以下行:

<runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30AD4FE6B2A6AEED" culture="neutral"/>
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0"/>
      </dependentAssembly>
    </assemblyBinding>
</runtime>

Ms​​Tests 似乎不需要这些步骤,但 Nunit 则需要。 如果我尝试从普通的 ConsoleApplication 创建此对象,则适用相同的修改。

除了 Daneau 的回答。除非根据此处的约定正确命名,否则 NUnit 不会加载 .config 文件: http://nunit.org/index.php?p=configFiles&r=2.6.4

根据他们的说明,将您的 app.config 文件复制到您的 NUnit 项目中,并为其指定与您的项目完全相同的名称。在您的情况下,名称应为 "UnitTestProject1.config"。将其与原始 app.config 文件一起放在根文件夹中。

现在 bindingRedirect 将被正确加载。