NUnit3:Assert.Throws with async Task

tik*_*noa 30 c# nunit asynchronous nunit-3.0

我正在尝试将测试移植到NUnit3并且收到System.ArgumentException:不支持'async void'方法,请改为使用'async Task'.

[Test]
public void InvalidUsername()
{
...
var exception = Assert.Throws<HttpResponseException>(async () => await client.LoginAsync("notarealuser@example.com", testpassword));
exception.HttpResponseMessage.StatusCode.ShouldEqual(HttpStatusCode.BadRequest); // according to http://tools.ietf.org/html/rfc6749#section-5.2
...
}
Run Code Online (Sandbox Code Playgroud)

Assert.Throws似乎采用TestDelegate,定义为:

public delegate void TestDelegate();
Run Code Online (Sandbox Code Playgroud)

因此ArgumentException.移植此代码的最佳方法是什么?

Zab*_*bbu 55

这是由Nunit解决的.您现在可以使用Assert.ThrowsAsync <>()

https://github.com/nunit/nunit/issues/1190

例:

Assert.ThrowsAsync<Exception>(() => YourAsyncMethod());
Run Code Online (Sandbox Code Playgroud)


arn*_*rni 7

我建议使用以下代码代替Assert.ThrowsAsync,因为它更易读:

// Option A
[Test]
public void YourAsyncMethod_Throws_YourException_A()
{
    // Act
    AsyncTestDelegate act = () => YourAsyncMethod();

    // Assert
    Assert.That(act, Throws.TypeOf<YourException>());
}

// Option B (local function)
[Test]
public void YourAsyncMethod_Throws_YourException_B()
{
    // Act
    Task Act() => YourAsyncMethod();

    // Assert
    Assert.That(Act, Throws.TypeOf<YourException>());
}
Run Code Online (Sandbox Code Playgroud)


小智 -5

你可以尝试使用这样的东西:

 try
 {
     await client.LoginAsync("notarealuser@example.com", testpassword);
 }
 catch (Exception ex)
 {
     Assert.That(ex, Is.InstanceOf(typeof (HttpResponseException)));
 }
Run Code Online (Sandbox Code Playgroud)