问题描述
我想知道的是如何断言异步方法在C#单元测试中抛出异常?我可以在Visual Studio 2012中使用 Microsoft.VisualStudio.TestTools.UnitTesting
编写异步单元测试,但还没有弄清楚如何测试异常。我知道xUnit.net也支持这种异步测试方法,虽然我还没有尝试过这个框架。
对于我的意思,代码定义了被测系统:
using System;
使用System.Threading.Tasks;
public class AsyncClass
{
public AsyncClass(){}
public Task< int> GetIntAsync()
{
throw new NotImplementedException();
}
}
此代码段定义了一个测试 TestGetIntAsync
for AsyncClass.GetIntAsync
。这是我需要输入如何完成 GetIntAsync
抛出异常的断言:
使用Microsoft.VisualStudio.TestTools.UnitTesting;
使用System.Threading.Tasks;
[TestClass]
public class TestAsyncClass
{
[TestMethod]
public async任务TestGetIntAsync()
{
var obj = new AsyncClass();
//如何断言抛出异常?
var rslt = await obj.GetIntAsync();
}
}
随意使用一些其他相关的单元测试框架Visual Studio一个,如xUnit.net,如果需要,或者你会认为这是一个更好的选择。
请尝试标记方法:
[ExpectedException(typeof(NotImplementedException))]
pre>
What I would like to know is how I can assert that an asynchronous method throws an exception, in a C# unit test? I am able to write asynchronous unit tests with
Microsoft.VisualStudio.TestTools.UnitTesting
in Visual Studio 2012, but have not figured out how to test for exceptions. I know that xUnit.net also supports asynchronous test methods in this way, although I haven't tried that framework yet.For an example of what I mean, the following code defines the system under test:
using System; using System.Threading.Tasks; public class AsyncClass { public AsyncClass() { } public Task<int> GetIntAsync() { throw new NotImplementedException(); } }
This code snippet defines a test
TestGetIntAsync
forAsyncClass.GetIntAsync
. This is where I need input on how to accomplish the assertion thatGetIntAsync
throws an exception: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(); } }
Feel free to employ some other relevant unit test framework than the Visual Studio one, such as xUnit.net, if necessary or you would argue that it's a better option.
解决方案Please try mark method with:
[ExpectedException(typeof(NotImplementedException))]
这篇关于我如何断言C#异步方法在单元测试中引发异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!