Could not load type 'Context' from assembly 'Microsoft.AspNetCore.Hosting'

1.1k views Asked by At

Running my integration tests for some controllers, I get this exception:

Error Message:
   System.TypeLoadException : Could not load type 'Context' from assembly
 'Microsoft.AspNetCore.Hosting, Version=3.1.5.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.

I've already checked this but not helpful Could not load type 'Context' from assembly 'Microsoft.AspNetCore.Hosting, Version=3.0.0.0

Here's the list of dependencies in unit test proj:

<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>
    <IsPackable>false</IsPackable>
  </PropertyGroup>
  <ItemGroup>
    <Content Include="..\..\src\MyMicroserviceActio.Api\appsettings.json" Link="appsettings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="FluentAssertions" Version="4.19.4" />
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.3.0-preview-20170628-02" />
    <PackageReference Include="Microsoft.AspNetCore.TestHost" Version="2.0.0" />
    <PackageReference Include="Moq" Version="4.7.142" />
    <PackageReference Include="xunit" Version="2.2.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.2.0" />  
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\..\src\MyMicroserviceActio.Api\MyMicroserviceActio.Api.csproj" />
  </ItemGroup>
</Project>

And here's an example of a test case:

private readonly TestServer _server;
private readonly HttpClient _client;

public HomeControllerTests()
{
    _server = new TestServer(WebHost.CreateDefaultBuilder()
        .UseStartup<Startup>());
    _client = _server.CreateClient();
}

[Fact]
public async Task home_controller_get_should_return_string_content()
{
    var response = await _client.GetAsync("/");
    response.EnsureSuccessStatusCode();

    var content = await response.Content.ReadAsStringAsync();

    content.Should().BeEquivalentTo("Hello from MyMicroserviceActio API!");
}

The whole project is github

1

There are 1 answers

2
eduherminio On BEST ANSWER

You need to bump Microsoft.AspNetCore.TestHost to a compatible 3.x version (PR submitted).