无法从程序集 'Microsoft.AspNetCore.Hosting' 加载类型 'Context'

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

运行 我对某些控制器进行了集成测试,我得到了这个异常:

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

我已经检查过了但没有帮助

这是单元测试项目中的依赖项列表:

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

下面是一个测试用例示例:

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!");
}

整个项目是github

您需要将 Microsoft.AspNetCore.TestHost 升级到兼容的 3.x 版本(已提交 PR)。