单元测试 .NET Core 3 Web API 控制器

Unit test .NET Core 3 Web API Controller

我在 .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));

您可以通过使用 async/await 编写测试来减少 1 个结果。

[Test]
public async Task Get_WhenCalled_ReturnNotFound()
{
    service = new Mock<IService>();
    controller = new MyController(service.Object);

    service.Setup(service => service.GetAsync(1)).ReturnsAsync((MyType)null);

    var result = await controller.Get(1);

    Assert.That(result.Result, Is.TypeOf<NotFoundResult>());
}