Sun
Sun

Reputation: 4718

Unit test .NET Core 3 Web API Controller

I have a controller in a .NET Core v3 web API project

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

I'm trying to write a unit test for the Get method using NUnit.

This is what I have and it works:

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

But in the assert I have to call result.Result.Result. It looks a bit odd. Can I get around this?

I've also tried the following line but it's the same:

service.Setup(service => service.GetAsync(1)).Returns(Task.FromResult((MyType)null));

Upvotes: 1

Views: 2280

Answers (1)

Durga Prasad
Durga Prasad

Reputation: 989

You can reduce 1 Result by writing the test using async/await.

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

Upvotes: 2

Related Questions