How to get content value in Xunit when result returned in IActionResult type

Depends on what you expect returned. From previous example you used an action like this.

[HttpGet("{id}")]
public IActionResult Get(string id) {        
    var r = unitOfWork.Resources.Get(id);

    unitOfWork.Complete();

    Models.Resource result = ConvertResourceFromCoreToApi(r);

    if (result == null) {
        return NotFound();
    } else {
        return Ok(result);
    }        
}

That method will either return a OkObjectResult or a NotFoundResult. If the expectation of the method under test is for it to return Ok() then you need to cast the result in the test to what you expect and then do your assertions on that

public void GetTest_Given_Id_Should_Return_OkObjectResult_With_Resource() {
    //Arrange
    var expected = "test";
    var controller = new ResourcesController(mockDb);

    //Act
    var actionResult = controller.Get("1");

    //Assert
    var okObjectResult = actionResult as OkObjectResult;
    Assert.NotNull(okObjectResult);

    var model = okObjectResult.Value as Models.Resource;
    Assert.NotNull(model);

    var actual = model.Description;
    Assert.Equal(expected, actual);
}

Leave a Comment