Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 291
J86 Avatar asked Sep 15 '17 09:09

J86


2 Answers

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()
{
  ...
}
like image 67
Stephen Cleary Avatar answered Nov 11 '22 11:11

Stephen Cleary


You need to receive result of function GetArtists() (not Task), like this:

var getArtistsResult = artistsController.GetArtists().Result;

Then you can cast it to OkObjectResult.

Or you can try to change your test like this :

[TestMethod]
public async Task GetArtists_ReturnsOKStatusCode()
{
  // arrange
  var artistsController = new ArtistsController(_mockPermissionsService.Object, _mockArtistsService.Object, _mockLogger.Object);
  // act
  var getArtistsResult = await artistsController.GetArtists();
  var okObjectResult = settings.Should().BeOfType<OkObjectResult>().Subject;
  var result = okObjectResult.Value.Should().BeAssignableTo<SomeType>();
}

I used some extending methods from FluentAssetions lib, its very useful.

like image 33
Merchezatter Avatar answered Nov 11 '22 10:11

Merchezatter