XUnit:如何断言 ASP.NET Core 中控制器抛出的异常

XUnit: How to assert exception thrown by the controller in ASP.NET Core

我在控制器内部有一个方法,当检查不正确时它会做一些检查,它会抛出错误。我将如何使用特定消息捕获 API 抛出的错误?

我对如何做出这些类型的断言感到困惑。

到目前为止,这是我的代码,但我没能捕捉到控制器抛出的错误。我做错了什么?

[Fact]
    public async Task AppendEmailBase64Dto_InvalidBase64_ReturnBadRequest()
    {
        // Arrange
        var emailControllerMocks = new EmailControllerMocks();
        var mockLogger = emailControllerMocks.MockLogger();
        var mockMapper = emailControllerMocks.MockMapper();
        var mockEmsWorkUnit = emailControllerMocks.MockEmsWorkUnit();
        var mockAzureBlob = emailControllerMocks.MockAzureBlobAndGetTemplate();

        // Setup
        var userRequestTemplateString = File.ReadAllText(@".\EmailController\UserRequestTemplate.txt");
        mockAzureBlob.Setup(blob => blob.GetHtmlBlob(It.IsAny<string>(), It.IsAny<Uri>()))
            .ReturnsAsync(userRequestTemplateString);


        // Act
        var emailController = new Controllers.ApiV10.EmailController(mockLogger.Object, mockMapper.Object, mockEmsWorkUnit.Object, mockAzureBlob.Object);
        var jsonString = File.ReadAllText(@".\EmailController\TemplateBase64Invalid.json");
        var testEmailBase64Dto = GeneralHelpers.Deserialize<EmailBase64Dto>(jsonString);

        var badRequestResult = await emailController.AppendEmailBase64Dto(testEmailBase64Dto);
        //var result = badRequestResult.Value as ObjectResult;
        //var errorMessage = badRequestResult.Value as List<string>;
        //var statusCode = badRequestResult.StatusCode;

        // Assert
        //Assert.Equal("The provided base64 template is not a valid base64 string", errorMessage[0]);
        //Assert.Equal(400, statusCode);
    }

使用 Assert.ThrowsAsync (the asynchronous counterpart of Assert.Throws) 断言抛出特定类型的异常。

在你的情况下,你需要这样的东西:

var ex = await Assert.ThrowsAsync<HttpException>(async () => await emailController.AppendEmailBase64Dto(testEmailBase64Dto));

显然调整 'HttpException' 以适应您期望的任何类型的异常。 您将无法在同一测试中检查 return 类型(因为抛出异常时 AppendEmailBase64Dto 不会 return ),因此您需要测试单独测试中的异常。