可能的重复:
如何使用 NUnit 测试异步方法,最终使用另一个框架? https://stackoverflow.com/questions/12191831/how-do-i-test-an-async-method-with-nunit-eventually-with-another-framework
我想知道的是如何在 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();
}
}
此代码片段定义了一个测试TestGetIntAsync
for 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();
}
}
如有必要,请随意使用 Visual Studio 以外的其他相关单元测试框架,例如 xUnit.net,否则您会认为这是一个更好的选择。
请尝试使用以下标记方法:
[ExpectedException(typeof(NotImplementedException))]
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)