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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With