How can I create an instance of HttpConfiguration in a NUnit test using the new csproj format?

193 views Asked by At

I created a unit test (with NUnit) that creates an instance of HttpConfiguration and it is working fine using the classical csproj format. The test succeeds. I also created a unit test (with xUnit) that does the same, using the new csproj format. This test succeeds too.

So far so good. Actually, I want to create a NUnit test using the new csproj format. This test fails by throwing a System.IO.FileLoadException referring to Newtonsoft.Json, Version=6.0.0.0 .

I find this really strange. In all my test projects, I added two packages in addition to the referred unit test framework: Microsoft.AspNet.WebApi.Core 5.2.7 and Newtonsoft.Json 12.0.3 .

Here is the csproj of my failing test:

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

and here is the unit test that succeeds in the old project format and fails in the new one.

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

Here are my test results:

aa

I am really surprised. My test succeeds with NUnit using the old csproj format. My test also succeeds when using xUnit and new csproj format. Therefore, it should not matter which format or framework I use. However, when I use NUnit combined with the new format, the test fails. How is this possible and how can I make this work? Version 12.0.3 for Newtonsoft.Json is not a show stopper for the 2 other tests, so neither it should be for the failing one.

My code can be found on GitHub too:

1

There are 1 answers

3
Peska On BEST ANSWER

Your NUnit "OldStyle" project is referencing Newtonsoft.Json version 6.0.4. That's why it's working - this version was installed with Microsoft.AspNet.WebApi.Core so there is no conflict. Your "NewStyle" project is referencing Newtonsoft.Json version 12.0.3 and with whe same version of Microsoft.AspNet.WebApi.Core there is a conflict.

If you upgrade Newtonsoft.Json to latest version in your "OldStyle" project, it will create binding redirects for you in 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>

Copy this config to your "NewStyle" project and everything will be working as expected.