【发布时间】:2020-08-06 11:39:24
【问题描述】:
我在 .NET Core v3 Web API 项目中有一个控制器
public class MyController : ControllerBase
{
private readonly IService service;
public MyController (IService service)
{
this.service= service;
}
HttpGet("{id}")]
public async Task<ActionResult<MyModel>> Get(int id)
{
var record= await service.GetAsync(id);
if (record== null)
return NotFound();
return Ok(Convert to model before returning);
}
}
我正在尝试使用 NUnit 为 Get 方法编写单元测试。
这就是我所拥有的,并且有效:
[Test]
public void Get_WhenCalled_ReturnNotFound()
{
service = new Mock<IService>();
controller = new MyController(service.Object);
service.Setup(service => service.GetAsync(1)).ReturnsAsync((MyType)null);
var result = controller.Get(1);
Assert.That(result.Result.Result, Is.TypeOf<NotFoundResult>());
}
但是在断言中我必须调用result.Result.Result。看起来有点奇怪。我可以解决这个问题吗?
我也尝试了以下行,但它是一样的:
service.Setup(service => service.GetAsync(1)).Returns(Task.FromResult((MyType)null));
【问题讨论】:
标签: c# .net-core nunit asp.net-core-webapi web-api-testing