如何使用 Fluent Assertions 抛出异常?

How could I throw an exception using Fluent Assertions?

我正在使用 client to interact with CloudMQTT API. I am trying to create a user but after trying the code provided below, I was not able to create a user. When using the code provided within the Github repository for this project, I noticed that I am unable to make use of a ShouldThrow() method (apparently it should be provided by Fluent Assertions).

我确实在 Whosebug 上找到了一个 post,它看起来与我遇到的问题非常相似。在问题中提到 FluentAssertions 不支持异步方法。然而,在客户端的示例代码中,我可以看到不管这个事实如何都使用了 ShouldThrow() 方法。

我怎样才能让 ShoudldThrow() 工作或者我什至需要它工作(因为我认为只有在应用单元测试时才应该在这段代码中需要它)?

这是目前尝试过的:

public static async void CreateCloudUser(ICloudMqttApi client)
{
    var users = await client.GetUsers();
    Console.WriteLine($"Creating a user. Current users available: {users.Count}");
    var expectedUser = new NewUser
    {
        Password = $"{Guid.NewGuid()}",
        Username = $"staging-{Guid.NewGuid()}",
    };

    var createUserResponse = await client.CreateUser(expectedUser);
    createUserResponse.IsSuccessStatusCode.Should().BeTrue();

    var actual = await client.GetUser(expectedUser.Username);
    actual.Should().NotBeNull();
    actual.Username.Should().Be(expectedUser.Username);

    //users.Should().Contain(u => u.Username == expectedUser.Username); // <-- This throws an exception as well, but not of importance for this specific question.

    Func<Task> verifyUser = async () => await client.GetUser(expectedUser.Username);
    verifyUser.ShouldThrow<ApiException>() // <-- Not recognized
            .And.StatusCode.Should().Be(HttpStatusCode.NotFound);

    Console.WriteLine($"Created a user. Current users available: {users.Count}");
}

客户端在调用方法之前按照客户端文档中提供的方式定义:

var client = CloudMqttApi.GetInstance("username", "password");

执行该方法前后用户计数将得到相同的数字(显然应该增加)。

鉴于所示代码的异步性质,语法应为

//...

var deleteResponse = await client.DeleteUser(expectedUser.Username);
deleteResponse.IsSuccessStatusCode.Should().BeTrue();

Func<Task> verifyUser = async () => await client.GetUser(expectedUser.Username);

var exceptionAssertion = await verifyUser.Should().ThrowAsync<ApiException>();
exceptionAssertion.And.StatusCode.Should().Be(HttpStatusCode.NotFound);

//...

引用FluentAssertions: Exceptions

同时避免使用 async void。具有函数 return Task

public static async Task CreateCloudUser(ICloudMqttApi client) {

    //...

}

引用Async/Await - Best Practices in Asynchronous Programming