akn*_*ds1 11 c# unit-testing exception async-await .net-4.5
我想知道的是如何断言异步方法在C#单元测试中抛出异常?我能够Microsoft.VisualStudio.TestTools.UnitTesting在Visual Studio 2012中编写异步单元测试,但还没有弄清楚如何测试异常.我知道xUnit.net也以这种方式支持异步测试方法,尽管我还没有尝试过这个框架.
以我的意思为例,以下代码定义了被测系统:
using System;
using System.Threading.Tasks;
public class AsyncClass
{
public AsyncClass() { }
public Task<int> GetIntAsync()
{
throw new NotImplementedException();
}
}
Run Code Online (Sandbox Code Playgroud)
此代码段定义了一个测试TestGetIntAsync对AsyncClass.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();
}
}
Run Code Online (Sandbox Code Playgroud)
如果需要,可以随意使用一些其他相关的单元测试框架,而不是Visual Studio,如xUnit.net,或者你会认为这是一个更好的选择.
pet*_*kyy 10
请尝试标记方法:
[ExpectedException(typeof(NotImplementedException))]
Run Code Online (Sandbox Code Playgroud)
第一选择是:
try
{
await obj.GetIntAsync();
Assert.Fail("No exception was thrown");
}
catch (NotImplementedException e)
{
Assert.Equal("Exception Message Text", e.Message);
}
Run Code Online (Sandbox Code Playgroud)
第二个选项是使用预期的异常属性:
[ExpectedException(typeof(NotImplementedException))]
Run Code Online (Sandbox Code Playgroud)
第三种选择是使用Assert.Throws:
Assert.Throws<NotImplementedException>(delegate { obj.GetIntAsync(); });
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6445 次 |
| 最近记录: |