I would like to test controllers.
Here is one of them:
[HttpGet("{id}")]
public async Task<ActionResult<AccountTypeDTO>> GetAccountTypeById(string id)
{
try
{
//Some stuffs
return Ok(accountTypeDTO);
}
catch
{
//Some stuffs
return Ok(accountTypeDTO);
}
}
In the test class, how to get the AccountTypeDTO
returned by the method?
I have tried something like that but without success:
var returnedDTO = _accountTypesController.GetAccountTypeById(createdId).Result as OkObjectResult;
EDIT:
The following works:
AccountTypeDTO returnedDTO =(AccountTypeDTO)((OkObjectResult)_accountTypesController.GetAccountTypeById(createdId).Result.Result).Value;
but probably a little bit messy.
Another option?
It's basically what you already found, but instead of hard casting you should use assert methods like Assert.IsType<T>()
.
Example:
// Act
var result = await _accountTypesController.GetAccountTypeById(createdId);
// Assert
var actionResult = Assert.IsType<ActionResult<AccountTypeDTO>>(result);
var okObjectResult = Assert.IsType<OkObjectResult>(actionResult.Result);
var returnValue = Assert.IsType<AccountTypeDTO>(okObjectResult.Value);
Official documentation: https://learn.microsoft.com/en-us/aspnet/core/mvc/controllers/testing?view=aspnetcore-7.0#test-actionresultt