.net - 如何检查是否在与 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));
解决方案
偶然我找到了解决方案: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<DomainException>(() => Client.PostAsJsonAsync(url, command));
我想要的方式捕获异常。
推荐阅读
- java - 我正在尝试使用 java 套接字使用两个不同的网络连接我的两台笔记本电脑。但它没有用
- apache-kafka - 限制 web 使用的 kafka ksqlDB 查询结果
- java - 从 IntelliJ 运行 Gradle 项目时,我可以排除构建输出吗?
- react-native - Flatlist 里面进入 Scrollview
- r - 如何在 R 中与 NA 值聚合
- arrays - 仅复制没有高级过滤器的过滤数据并将原始过滤器保留在原始表上
- encoding - 根据前缀确定 HSM_KX 标头长度
- c# - 无法定位元素——OpenQA.Selenium.NoSuchElementException
- go - Gopls 仅在我在 Macos Big Sur 中使用 sudo 执行 vim 或 vscode 时才有效
- c++ - 检查平衡括号代码的行为不符合预期