gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 08:59:33 24 4
gpt4 key购买 nike

<分区>

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

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

为了说明我的意思,下面的代码定义了被测系统:

using System;
using System.Threading.Tasks;

public class AsyncClass
{
public AsyncClass() { }

public Task<int> GetIntAsync()
{
throw new NotImplementedException();
}
}

此代码片段为 AsyncClass.GetIntAsync 定义了一个测试 TestGetIntAsync。这是我需要输入有关如何完成 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,否则您会认为这是更好的选择。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com