You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 6 Web API中如何用xUnit测试InternalServerError?

如何断言ASP.NET Core单元测试中的500内部服务器错误

针对你的测试场景,需根据控制器的异常处理逻辑编写对应断言,以下是两种常见场景的实现:

场景1:使用[ApiController]自动异常处理

如果控制器标记了[ApiController]特性,未处理的异常会被框架自动包装为包含ProblemDetails的ObjectResult,状态码固定为500。此时完整测试代码如下:

[Fact]
public async Task ShouldReturnInternalServerError_OnUnhandledError()
{
    // arrange
    var Id = fixture.Create<string>();
    List<Emp> emps = fixture.Create<List<Emp>>();
    var exception = new Exception("Internal Server Error");

    factsService.Setup(x => x.SetEmps(Id, emps)).Throws(exception);

    // act
    var response = await EmpController.SetEmps(Id, emps);

    // assert
    response.Should().NotBeNull();
    
    // 断言返回类型为ObjectResult且状态码为500
    var objectResult = response.Should().BeAssignableTo<ObjectResult>().Subject;
    objectResult.StatusCode.Should().Be(StatusCodes.Status500InternalServerError);

    // 可选:断言ProblemDetails中的错误详情(匹配异常消息)
    var problemDetails = objectResult.Value.Should().BeAssignableTo<ProblemDetails>().Subject;
    problemDetails.Detail.Should().Contain(exception.Message);
}

场景2:控制器手动捕获异常返回500

如果控制器手动捕获异常并返回500状态码(例如使用StatusCode(500, errorMessage)),则断言逻辑可简化为:

// 替换原assert部分
response.Should().NotBeNull();
var objectResult = response.Should().BeAssignableTo<ObjectResult>().Subject;
objectResult.StatusCode.Should().Be(StatusCodes.Status500InternalServerError);
// 断言返回的错误消息与预期一致
objectResult.Value.Should().Be("Internal Server Error");

关键注意点

  • 使用StatusCodes.Status500InternalServerError常量替代硬编码的500,提升代码可读性和维护性;
  • FluentAssertions的.Subject方法可获取断言后的对象,用于后续属性验证;
  • 代码中修正了拼写错误:fixure改为fixture(符合AutoFixture实例命名规范)。

内容的提问来源于stack exchange,提问作者user21364415

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 03:32:22