如果在IActionResult类型中返回结果,如何在Xunit中获取内容值

Jul*_* C. 20 c# unit-testing xunit asp.net-core asp.net-core-webapi

我有一个使用Xunit的单元测试项目,我们正在测试的方法返回IActionResult.

我看到有些人建议使用"NegotiatedContentResult"获取内容,IActionResult但这在Xunit中不起作用.

所以我想知道如何获取IActionResultXunit中的内容值?

测试代码示例如下:

public void GetTest()
{
    var getTest = new ResourcesController(mockDb);

    var result = getTest.Get("1");

    //Here I want to convert the result to my model called Resource and
    //compare the attribute Description like below.
    Resource r = ?? //to get the content value of the IActionResult

    Assert.Equal("test", r.Description);
}
Run Code Online (Sandbox Code Playgroud)

有没有人知道如何在XUnit中这样做?

Nko*_*osi 28

取决于你期望的回报.从前面的示例中,您使用了这样的操作.

[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);
    }        
}
Run Code Online (Sandbox Code Playgroud)

该方法将返回a OkObjectResult或a NotFoundResult.如果测试方法的期望是它返回,Ok()那么你需要将测试中的结果转换为你期望的,然后对你的断言进行断言

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);
}
Run Code Online (Sandbox Code Playgroud)

  • 如果在ok中返回动态对象怎么办,例如:Ok(new {token ="",expiration = DateTime.Now.AddHours(1)}; (3认同)