我如何断言C#async方法在单元测试中抛出异常?

我如何断言C#async方法在单元测试中抛出异常?,c#,unit-testing,exception,.net-4.5,async-await,C#,Unit Testing,Exception,.net 4.5,Async Await,可能重复: 我想知道的是,在C#单元测试中,如何断言异步方法引发异常?我能够在Visual Studio 2012中使用Microsoft.VisualStudio.TestTools.UnitTesting编写异步单元测试,但还没有弄清楚如何测试异常。我知道xUnit.net也以这种方式支持异步测试方法,尽管我还没有尝试过这种框架 下面的代码定义了测试中的系统,以说明我的意思: using System; using System.Threading.Tasks; public class

可能重复:

我想知道的是,在C#单元测试中,如何断言异步方法引发异常?我能够在Visual Studio 2012中使用
Microsoft.VisualStudio.TestTools.UnitTesting
编写异步单元测试,但还没有弄清楚如何测试异常。我知道xUnit.net也以这种方式支持异步测试方法,尽管我还没有尝试过这种框架

下面的代码定义了测试中的系统,以说明我的意思:

using System;
using System.Threading.Tasks;

public class AsyncClass
{
    public AsyncClass() { }

    public Task<int> GetIntAsync()
    {
        throw new NotImplementedException();
    }
}    

如有必要,请随意使用Visual Studio框架以外的其他相关单元测试框架,如xUnit.net,否则您会认为这是一个更好的选择。

请尝试使用以下标记方法:

[ExpectedException(typeof(NotImplementedException))]
第一种选择是:

try
{
   await obj.GetIntAsync();
   Assert.Fail("No exception was thrown");
}
catch (NotImplementedException e)
{      
   Assert.Equal("Exception Message Text", e.Message);
}
第二个选项是使用预期的异常属性:

[ExpectedException(typeof(NotImplementedException))]
第三个选项是使用Assert.Throws:

Assert.Throws<NotImplementedException>(delegate { obj.GetIntAsync(); });
Assert.Throws(委托{obj.GetIntAsync();});
尝试使用第三方物流:

[ExpectedException(typeof(NotImplementedException))]
[TestMethod]
public void TestGetInt()
{
    TaskFactory.FromAsync(client.BeginGetInt, client.EndGetInt, null, null)
               .ContinueWith(result =>
                   {
                       Assert.IsNotNull(result.Exception);
                   }
}

@JonSkeet不是真的,因为这是专门关于检查异常的。虽然我现在明白了,但它与VisualStudio框架没有区别。然而,对于xUnit.net,我仍然不知道该怎么做。@JonSkeet最初我同意,但现在我不同意。如果这个问题是正确的,因为Microsoft的单元测试已经支持异步测试,那么您对另一个问题的回答在这里并不适用。唯一的问题是重写测试时,测试是否存在异常。@hvd:在这种情况下,问题似乎与异步无关-当然给出的答案并不真正依赖于异步部分。@JonSkeet,如我所说,我没有想到VisualStudio单元测试框架通过方法属性来处理这个问题。我仍然想知道如何在xUnit.net上实现同样的功能,但我想最好还是留给另一个问题来解决…@aknuds1:我个人强烈建议在可用的地方使用Assert.Throws。它限制了您期望抛出异常的范围。但我的观点是,异步部分是一个转移视线的问题——在这种情况下,它们完全是测试的正交方面。我没有想到异常是通过这个框架中的属性断言的。谢谢
Assert.IsTrue(true)
的目的是什么?@svick:对!我们可以删除它:)@svick有些人使用Assert.IsTrue(true)来向任何阅读代码的人表明,只要在代码中达到该点就表示成功(如果没有Assert.IsTrue(true),可能看起来作者忘记输入Assert)
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Threading.Tasks;

[TestClass]
public class TestAsyncClass
{
    [TestMethod]
    [ExpectedException(typeof(NotImplementedException))]
    public async Task TestGetIntAsync()
    {
        var obj = new AsyncClass();
        // How do I assert that an exception is thrown?
        var rslt = await obj.GetIntAsync();
    }
}
[ExpectedException(typeof(NotImplementedException))]
[TestMethod]
public void TestGetInt()
{
    TaskFactory.FromAsync(client.BeginGetInt, client.EndGetInt, null, null)
               .ContinueWith(result =>
                   {
                       Assert.IsNotNull(result.Exception);
                   }
}