2012-09-03 145 views
8

可能重复:
How do I test an async method with NUnit, eventually with another framework?如何声明C#异步方法在单元测试中引发异常?

我想知道的是,我怎么能断言异步方法抛出一个异常,在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(); 
    } 
}  

此代码段定义了一个测试TestGetIntAsyncAsyncClass.GetIntAsync。这是我需要在如何实现这一目标GetIntAsync抛出异常的断言输入:

using Microsoft.VisualStudio.TestTools.UnitTesting; 
using System.Threading.Tasks; 

[TestClass] 
public class TestAsyncClass 
{ 
    [TestMethod] 
    public async Task TestGetIntAsync() 
    { 
     var obj = new AsyncClass(); 
     // How do I assert that an exception is thrown? 
     var rslt = await obj.GetIntAsync(); 
    } 
} 

随意聘请多名Visual Studio的一个,如xUnit.net一些其他相关的单元测试框架,如果有必要或你会认为这是一个更好的选择。

+0

@JonSkeet不是真的,因为这是专门关于检查异常。尽管我现在看到它与Visual Studio框架没有任何区别。然而,对于xUnit.net,我仍然不确定如何去做。 – aknuds1

+0

@JonSkeet最初我同意了,但现在我不同意。如果这个问题是正确的,因为微软的单元测试已经支持异步测试,你对这个问题的答案在这里并不适用。唯一的问题是重写测试,以便测试异常。 – hvd

+0

@hvd:在这种情况下,听起来像这个问题有*无关*与异步 - 当然,给出的答案不依赖于异步部分。 –

回答

9

请尝试用标记方法:

[ExpectedException(typeof(NotImplementedException))] 
+0

我没有想到,在这个框架中,异常是通过属性来声明的。谢谢! – aknuds1

+0

不客气! :) –

6

第一种选择是:

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(); }); 
+0

'Assert.IsTrue(true)'的目的是什么? – svick

+0

@svick:对!我们可以将其删除:) – CloudyMarble

+1

@svick有些人使用Assert.IsTrue(true)向任何读取代码的人指示,代码中的代码表示成功(没有Assert.IsTrue(true),它可能看起来像作者忘了提出声明) – Rune

2
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(); 
    } 
} 
0

尝试使用TPL:

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