我有以下单元测试用例,我想对 500 - 内部服务错误进行测试。我坚持比较什么,这样它就会通过。
[Fact]
public async Task ShouldReturnInternalServerError_OnUnhandledError()
{
//arrange
var Id = fixure.Create<string>();
List<Emp> emps = fixure.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();
response.Should().BeAssignableTo<ActionResult>();
//this is for bad request
//response.Should().BeAssignableTo<BadRequestObjectResult>();
//not sure what to match here below for InternalServerError
response.Should().
}
这样的单元测试是不可能的,您需要使用集成测试方法。对于这种方法,您只能检查
EmpController.SetEmps
是否抛出正确的异常(即EmpController.Invoking(y => y.SetEmps(Id, emps).Should().Throw<...>().WithMessage(...)
)。控制器动作/方法不会执行任何魔法来处理未处理的异常,它是在“稍后”在管道中完成的。
另请注意,HTTP 500 的单元测试可能毫无意义。