gpt4 book ai didi

c# - 如何使用 Fluent Assertions 抛出异常?

转载 作者:行者123 更新时间:2023-12-02 04:27:33 29 4
gpt4 key购买 nike

我正在使用 clientCloudMQTT API 互动。我正在尝试create a user但在尝试下面提供的代码后,我无法创建用户。当使用此项目的 Github 存储库中提供的代码时,我注意到我无法使用 ShouldThrow() 方法(显然它应该由 Fluent Assertions 提供)。

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

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

这是迄今为止尝试过的:

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。让函数返回 Task

public static async Task CreateCloudUser(ICloudMqttApi client) {

//...

}

引用Async/Await - Best Practices in Asynchronous Programming

关于c# - 如何使用 Fluent Assertions 抛出异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59749523/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com