我如何断言C#异步方法在单元测试中引发异常?

编程入门 行业动态 更新时间:2024-10-25 06:22:55
本文介绍了我如何断言C#异步方法在单元测试中引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

可能重复: 如何使用NUnit测试异步方法,最终使用另一个框架?

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

对于我的意思,代码定义了被测系统:

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,如果需要,或者你会认为这是一个更好的选择。

解决方案

请尝试标记方法:

[ExpectedException(typeof(NotImplementedException))] pre>

Possible Duplicate: How do I test an async method with NUnit, eventually with another framework?

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 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 for AsyncClass.GetIntAsync. This is where I need input on how to accomplish the assertion that GetIntAsync 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, if necessary or you would argue that it's a better option.

解决方案

Please try mark method with:

[ExpectedException(typeof(NotImplementedException))]

更多推荐

我如何断言C#异步方法在单元测试中引发异常?

本文发布于:2023-10-31 05:06:19,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1545089.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:断言   单元   异常   方法   测试中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!