【问题标题】:Could not load type 'Context' from assembly 'Microsoft.AspNetCore.Hosting'无法从程序集“Microsoft.AspNetCore.Hosting”加载类型“上下文”
【发布时间】:2020-11-20 19:56:52
【问题描述】:

为一些控制器运行我的集成测试,我得到了这个异常:

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

我已经检查过了,但没有帮助 Could not load type 'Context' from assembly 'Microsoft.AspNetCore.Hosting, Version=3.0.0.0

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

<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

【问题讨论】:

    标签: .net-core integration-testing asp.net-core-testhost


    【解决方案1】:

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

    【讨论】:

    • 我经常使用TestHost,所以我知道它需要一个包才能工作。错误信息告诉你它无法从Microsoft.AspNetCore.Hosting, Version=3.1.5.0 加载类型,所以我首先检查的是.csproj 中相关包的版本。根据我的经验,如果 n
    • 谢谢@eduherminio。 TBH,我即将将我的项目移植到 .Net 5
    猜你喜欢
    • 2019-12-09
    • 2016-01-02
    • 1970-01-01
    • 2012-05-05
    • 2010-09-19
    • 2017-11-26
    • 2020-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多