单元测试任务<iactionresult>

时间:2017-09-15 09:32:07

标签: c# unit-testing asp.net-core mstest

我正在研究.Net Core Web API应用程序。我的控制器上有以下方法:

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

我想写一个测试,断言我确实得到了200 OK结果。

我尝试了以下内容:

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

但是在我投射到OkObjectResult的行上我收到错误。它说我无法将类型Task<IActionResult>转换为OkObjectResult

2 个答案:

答案 0 :(得分:5)

调用异步方法时需要使用await

var getArtistsResult = await artistsController.GetArtists();

这反过来使您的测试方法async Task

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

答案 1 :(得分:4)

您需要接收函数GetArtists()(不是Task)的结果,如下所示:

var getArtistsResult = artistsController.GetArtists().Result;

然后你可以将它转换为OkObjectResult。

或者您可以尝试更改您的测试:

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

我使用了一些来自FluentAssetions lib的扩展方法,它非常有用。