【问题标题】:How to check if exception is thrown in Integration Test with xUnit (.net core)?如何检查是否在与 xUnit(.net 核心)的集成测试中引发异常?
【发布时间】:2019-07-26 18:29:20
【问题描述】:

我想知道如何创建测试(使用 .NET Core 2.2 WebApi 中的 xUnit)来检查我的 API 端点是否引发特定异常。

这是我目前所拥有的:

[Theory]
[InlineData("/values/sample")]
public async Task Sample_WhenCreatingInvalidSampleData_ThenExceptionIsThrown(string url)
{
    // given
    var command = new AddSampleCommand { Name = "test" };

    // when
    var httpResponse = await Client.PostAsJsonAsync(url, command);

    // then
    var stringResponse = await httpResponse.Content.ReadAsStringAsync();
    stringResponse.ShouldContain("DomainException");
    stringResponse.ShouldContain("is not allowed");
}

它工作正常,但我认为我的解决方案是一个坏把戏。

我这样做是因为在抛出此异常时我无法捕获此异常我只能获取 httpResponse(即 html)然后解析并确保在这种情况下包含异常名称 stringResponse.ShouldContain("DomainException"); 和一些异常消息 stringResponse.ShouldContain("is not allowed");

我不知道如何以不同的方式做到这一点。因为它不会工作

Should.Throw<DomainException>(() => Client.PostAsJsonAsync(url, command)); 

【问题讨论】:

  • 这些是客户端和服务器之间的独立关注点。除了返回的 http 响应之外,客户端不会知道服务器上的实际异常。检查状态码和预期的内容。
  • 你能利用中间件管道吗?你用的是什么服务器?
  • 这可能是XY problem
  • @Nkosi 已解决,请查看我的答案。

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


【解决方案1】:

我偶然找到了解决方案:D 不知道为什么它会起作用,但最重要的是它有帮助。

所以我必须创建自己的Startup 进行测试

public class TestStartup : Startup
{
    public TestStartup(IConfiguration configuration) : base(configuration)
    {
    }
}

我将 TestStartup 用法添加到 CustomWebApplicationFactory 并将 ApplicationPart 从原始应用添加到配置

public class CustomWebApplicationFactory<TTestStartup, TStartup> : WebApplicationFactory<TStartup>
    where TTestStartup: class
    where TStartup : class
{
    protected override IWebHostBuilder CreateWebHostBuilder()
    {
        return WebHost.CreateDefaultBuilder(null)
            .UseStartup<TTestStartup>();
    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {    
        builder.ConfigureServices(services =>
        {
            services.AddMvc().AddApplicationPart(typeof(TStartup).Assembly);

            // rest configuration
        }
    }
}

多亏了我可以像我想要的那样通过断言或Should.Throw&lt;DomainException&gt;(() =&gt; Client.PostAsJsonAsync(url, command)); 轻松捕获异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-07
    • 2021-11-29
    • 1970-01-01
    • 2020-04-02
    • 2023-03-14
    • 1970-01-01
    • 2017-01-05
    • 1970-01-01
    相关资源
    最近更新 更多