首页 > 解决方案 > 如何检查是否在与 xUnit(.net 核心)的集成测试中引发异常?

问题描述

我想知道如何创建测试(在 .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)); 

标签: .netasp.net-coreintegration-testingxunit

解决方案


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

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

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

我添加了TestStartup使用,CustomWebApplicationFactoryApplicationPart从原始应用程序添加到配置

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<DomainException>(() => Client.PostAsJsonAsync(url, command));我想要的方式捕获异常。


推荐阅读