我创建了一个测试,看起来像这样:

[Test]
public async Task MemberCannotCreateConfirmedUser()
{
    var services = UserContext.GivenServices();
    await services.LoginAsync(new Claim("User", "Member"));
    Assert.That(await services.WhenCreateUserAsync("AAAB", "AAAB", "AAAB", "FIN", emailConfirmed: true), Throws.TypeOf<ArgumentException>());
}


实际引发错误的代码如下所示:

var principal = _httpContext.User as ClaimsPrincipal;
var isAdmin = principal?.FindFirst("Administrator") != null;
if (!isAdmin)
{
    if (model.EmailConfirmed) throw new ArgumentException("Only an administrator can confirm a new user");
}


当我运行测试时,它失败并指出:


  System.ArgumentException:只有管理员可以确认新用户


但是可以肯定的是,我正在测试。它应该通过,因为它引发ArgumentException错误?

最佳答案

原来我只是在做错误的断言。因为委托是异步的,所以我需要进行异步检查。因此,用以下内容代替我的声明:

Assert.ThrowsAsync<ArgumentException>(async () => await services.WhenCreateUserAsync("AAAB", "AAAB", "AAAB", "FIN", emailConfirmed: true));


解决了问题

10-06 00:05