简体   繁体   中英

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

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()
{
  ...
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM