【发布时间】:2020-12-04 08:17:43
【问题描述】:
我有一个 API,其返回类型为 IActionResult。伪代码如下
public async Task<IActionResult> Getdata()
{
var result = await _report.Getall(DateTime.UtcNow);
}
我正在尝试为此编写单元测试,如下所示。
[Test]
public async Task Error_code()
{
_report.Setup(r => r.Getall(It.IsAny<DateTime>())).ThrowsAsync(new Exception("Error Message"));
var result = await _reportCnt.Getdata(); //_reportCnt is object of the Controller
Assert.AreEqual("Error Message",reuslt);
}
但我面临的问题是,一旦从 API 抛出错误,它就不会断言,单元测试失败并出现错误Exception of type 'System.Exception' was thrown。
这三种方法我都试过了
var result = await _reportCnt.Getdata() as ObjectResult;
var result = await _reportCnt.Getdata() as ActionResult;
var result = await _reportCnt.Getdata() as ExceptionResult;
但不工作,抛出同样的问题。
我在这里缺少什么或任何建议?
【问题讨论】:
-
尝试使用 [ExpectedException(typeof(Exception))] 属性注释您的测试方法。 [Test] 属性的正下方。
-
我正在使用 NUnit,但 MsTest 中存在 ExpectedException。但是在 NUnit 中我们仍然有 Assert.throwsAsync()。但尝试相同它会引发不同的问题。您仍然可以提供代码参考或一些伪代码吗?
标签: c# unit-testing .net-core nunit asp.net-core-webapi