如何断言 C# 异步方法在单元测试中引发异常? [英] How can I assert that a C# async method throws an exception in a unit test?

查看:41
本文介绍了如何断言 C# 异步方法在单元测试中引发异常?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
如何测试异步方法与 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.

举个例子,下面的代码定义了被测系统:

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

此代码段为AsyncClass.GetIntAsync 定义了一个测试TestGetIntAsync.这是我需要输入如何完成 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天全站免登陆