简体   繁体   English

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

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

I have a unit test project using Xunit and the method we are testing returns IActionResult . 我有一个使用Xunit的单元测试项目,我们测试的方法返回IActionResult

I saw some people suggest using "NegotiatedContentResult" to get the content of the IActionResult but that doesn't work in Xunit. 我看到有人建议使用“NegotiatedContentResult”来获取IActionResult的内容,但这在Xunit中不起作用。

So I wonder how to get the content value of an IActionResult in Xunit? 所以我想知道如何在IActionResult中获取IActionResult的内容值?

Test code example is provided below: 测试代码示例如下:

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

Does anyone know how to do this in XUnit? 有没有人知道如何在XUnit中这样做?

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 . 该方法将返回OkObjectResultNotFoundResult 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 如果测试方法的期望是它返回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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM