我正在使用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?)
。
我做错了什么?
答案 0 :(得分:4)
据我所知,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 ) );
}
}