当IActionResult类型返回结果时

当IActionResult类型返回结果时

本文介绍了当IActionResult类型返回结果时,如何在Xunit中获取内容值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a unit test project using Xunit and the method we are testing returns IActionResult.

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

I saw some people suggest using "NegotiatedContentResult" to get the content of the IActionResult but that doesn't work in Xunit.

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

So I wonder how to get the content value of an IActionResult in Xunit?

下面提供了测试代码示例:

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

有人知道如何在XUnit中执行此操作吗?

Does anyone know how to do this in 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);
    }
}

该方法将返回OkObjectResultNotFoundResult.如果对被测方法的期望是返回Ok(),那么您需要将测试中的结果强制转换为期望的值,然后对之进行断言

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

这篇关于当IActionResult类型返回结果时,如何在Xunit中获取内容值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 23:49