c# - 如何处理 xUnit .net 的 Assert.Throws<T> 中任务抛出的异常?

标签 c# async-await c#-5.0 xunit.net

以下异步xUnit.netlambda 测试标有 async修饰符通过报告没有抛出异常而失败:

    [Theory, AutoWebData]
    public async Task SearchWithNullQueryThrows(
        SearchService sut,
        CancellationToken dummyToken)
    {
        // Fixture setup
        // Exercise system and verify outcome
        Assert.Throws<ArgumentNullException>(async () =>
            await sut.SearchAsync(null, dummyToken));
        // Teardown
    }

确保 ArgumentNullException实际上抛出了我明确使用了 try-catch堵塞。它有效,但是生成的代码并不干净(与第一个测试相比):

[Theory, AutoWebData]
public async Task SearchWithNullQueryThrows(
    SearchService sut,
    CancellationToken dummyToken)
{
    // Fixture setup
    var expected = typeof(ArgumentNullException);
    Type actual = null;
    // Exercise system
    try
    {
        await sut.SearchAsync(null, dummyToken);
    }
    catch (ArgumentNullException e)
    {
        actual = e.GetType();
    }
    // Verify outcome
    Assert.Equal(expected, actual);
    // Teardown
}

为什么 Assert.Throws<T>lambda标有 async修饰符失效?

最佳答案

更新

这已在 xUnit 2 中解决,添加了 Assert.ThrowsAsync .


我怀疑 Assert.Throws不是 async -知道的。我建议向 xUnit 团队提出这个问题,建议 ThrowsAsync被添加。

async在这种情况下,代表返回 TaskTask<T> , 和 ArgumentNullException不会直接从委托(delegate)中抛出;相反,它被放置在 Task 上(Task.Exception.InnerException)。 Assert.Throws期望异常直接从委托(delegate)中抛出,而不是放在返回值的属性上。

您可以创建自己的 AssertEx.ThrowsAsync因此:

public static async Task ThrowsAsync<TException>(Func<Task> func)
{
  var expected = typeof(TException);
  Type actual = null;
  try
  {
    await func();
  }
  catch (Exception e)
  {
    actual = e.GetType();
  }
  Assert.Equal(expected, actual);
}

可以这样使用:

[Theory, AutoWebData]
public async Task SearchWithNullQueryThrows(
    SearchService sut,
    CancellationToken dummyToken)
{
    // Fixture setup
    // Exercise system and verify outcome
    await AssertEx.ThrowsAsync<ArgumentNullException>(async () =>
        await sut.SearchAsync(null, dummyToken));
    // Teardown
}

我在 MSTest 中使用了类似的方法。

关于c# - 如何处理 xUnit .net 的 Assert.Throws<T> 中任务抛出的异常?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14084923/

相关文章:

c# - 我应该用 "new Thread"替换我所有的 "Task.Factory.StartNew"吗?

c# - 许多读者,一个作者 - 是否有可能避免锁定?

c# - TcpListener : how to stop listening while awaiting AcceptTcpClientAsync()?

c# - 为什么 C# 调用方信息属性需要默认值?

c# - 将 Application Insights 与 ILoggerFactory 结合使用

c# - 将复杂的json反序列化为类似字典的结构

javascript - react .js : Will multiple async setState method calls always re-render after and impact performance?

node.js - 如何在 Node 中的函数调用中等待回调?

c# - 为什么 Office 365 OutlookServices (v1.0.34) .Net 客户端库无限期挂起?

C# .net 4.5 异步委托(delegate)