NUnit3:Assert.Throws with async Task

时间:2014-11-19 18:49:59

标签: c# asynchronous nunit 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
...
}

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

public delegate void TestDelegate();

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

5 个答案:

答案 0 :(得分:46)

这是由Nunit解决的。您现在可以使用Assert.ThrowsAsync&lt;&gt;()

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

示例:

Assert.ThrowsAsync<Exception>(() => YourAsyncMethod());

答案 1 :(得分:4)

我建议使用以下代码而不是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>());
}

答案 2 :(得分:1)

为了确保抛出异常,如果您选择使用catch块,最好不要在catch块中断言。这样,您可以确保抛出了正确的异常类型,否则您将获得空引用或未捕获的异常异常。

HttpResponseException expectedException = null;
try
{
    await  client.LoginAsync("notarealuser@example.com", testpassword));         
}
catch (HttpResponseException ex)
{
    expectedException = ex;
}

Assert.AreEqual(HttpStatusCode.NoContent, expectedException.Response.BadRequest);

答案 3 :(得分:0)

我最终编写了一个反映NUnit功能的静态函数。在https://github.com/nunit/nunit/issues/464就此进行了一次完整的对话。

public static async Task<T> Throws<T>(Func<Task> code) where T : Exception
{
    var actual = default(T);

    try
    {
        await code();
        Assert.Fail($"Expected exception of type: {typeof (T)}");
    }
    catch (T rex)
    {
        actual = rex;
    }
    catch (Exception ex)
    {
        Assert.Fail($"Expected exception of type: {typeof(T)} but was {ex.GetType()} instead");
    }

    return actual;
}

然后从我的测试我可以使用它,如

var ex = await CustomAsserts.Throws<HttpResponseException>(async () => await client.DoThings());
Assert.IsTrue(ex.Response.StatusCode == HttpStatusCode.BadRequest);

答案 4 :(得分:-3)

您可以尝试使用以下内容:

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