我怎么可以断言,一个C#异步方法抛出一个单元测试的异常? [英] How can I assert that a C# async method throws an exception in a unit test?

查看:616
本文介绍了我怎么可以断言,一个C#异步方法抛出一个单元测试的异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/12191831/how-do-i-test-an-async-method-with-nunit-eventually-with-another-framework\">How我测试一个异步方法与NUnit的,最终与另一个框架?

我想知道什么是我可以断言,一个异步方法抛出一个异常,在C#单元测试?我能够在Visual Studio 2012年编写异步单元测试 Microsoft.VisualStudio.TestTools.UnitTesting ,但还没有想出如何测试例外。我知道,xUnit.net也支持这样的异步的测试方法,虽然我没有试过,但框架

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.

有关我的意思的例子,下面的code定义被测系统:

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

这code片段定义测试 TestGetIntAsync AsyncClass.GetIntAsync 。这就是我需要如何完成断言 GetIntAsync 抛出一个异常,输入:

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

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

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.

推荐答案

请尝试用标记方法:

[ExpectedException(typeof(NotImplementedException))]

这篇关于我怎么可以断言,一个C#异步方法抛出一个单元测试的异常?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆