Search code examples
c#unit-testingasp.net-coremstest

Unit Test Task<IActionResult>


I am working on a .Net Core Web API application. I have the following method on my controller:

[HttpGet]
public async Task<IActionResult> GetArtists()
{
  var permissions = await _permissionsService.GetPermissionsAsync(HttpContext);
  var artists = _artistsService.GetAllArtists(permissions.UserId, permissions.IsAdministrator);
  return Ok( new { artists });
}

I want to write a test that would assert that I am indeed getting a 200 OK Result.

I've tried the following:

[TestMethod]
public void GetArtists_ReturnsOKStatusCode()
{
  // arrange
  var artistsController = new ArtistsController(_mockPermissionsService.Object, _mockArtistsService.Object, _mockLogger.Object);
  // act
  var getArtistsResult = artistsController.GetArtists();
  var okResult = getArtistsResult as OkObjectResult;

  Assert.IsInstanceOfType(okResult, OkObjectResult)
}

But I get an error on the line where I am casting to OkObjectResult. It says I can't convert type Task<IActionResult> to OkObjectResult


Solution

  • You need to use await when calling asynchronous methods:

    var getArtistsResult = await artistsController.GetArtists();
    

    This in turn makes your test method async Task:

    [TestMethod]
    public async Task GetArtists_ReturnsOKStatusCode()
    {
      ...
    }