【问题标题】:Asserting exceptions in async delegates在异步委托中断言异常
【发布时间】:2016-08-10 19:07:59
【问题描述】:

我使用的是 NUnit 3。我写了一个扩展方法:

public static T ShouldThrow<T>(this TestDelegate del) where T : Exception {
  return Assert.Throws(typeof(T), del) as T;
}

这允许我这样做:

TestDelegate del = () => foo.doSomething(null);
del.ShouldThrow<ArgumentNullException>();

现在我想要类似的异步:

AsyncTestDelegate del = async () => await foo.doSomething(null);
del.ShouldThrowAsync<ArgumentNullException>();

所以我写了这个:

public static async Task<T> ShouldThrowAsync<T>(this AsyncTestDelegate del) where T : Exception {
  return (await Assert.ThrowsAsync(typeof(T), del)) as T;
}

但这不起作用:'Exception' does not contain a definition for 'GetAwaiter' and no extension method 'GetAwaiter' accepting a first argument of type 'Exception' could be found (are you missing a using directive or an assembly reference?)

我做错了什么?

【问题讨论】:

    标签: c# unit-testing asynchronous async-await nunit


    【解决方案1】:

    据我所知,Assert.ThrowsAsync 不会返回 Task,因此无法等待。从您的扩展方法中删除 await

    public static T ShouldThrowAsync<T>(this AsyncTestDelegate del) where T : Exception {
      return Assert.ThrowsAsync(typeof(T), del) as T;
    }
    

    来自docs 的示例用法。请注意,Assert.ThrowsAsync 返回一个 MyException 并且 await 在委托中。

    [TestFixture]
    public class UsingReturnValue
    {
      [Test]
      public async Task TestException()
      {
        MyException ex = Assert.ThrowsAsync<MyException>(async () => await MethodThatThrows());
    
        Assert.That( ex.Message, Is.EqualTo( "message" ) );
        Assert.That( ex.MyParam, Is.EqualTo( 42 ) ); 
      }
    }
    

    【讨论】:

    • 是的,我自动假设,因为它是一个委托,所以需要等待断言...... doh!
    • 根据 MS 命名约定,它应该是。 ;)
    猜你喜欢
    • 2017-06-23
    • 2013-03-16
    • 2010-11-27
    • 1970-01-01
    • 2012-06-08
    • 2021-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多