我有一个使用Xunit的单元测试项目,我们测试的方法返回IActionResult
。
我看到有人建议使用" NegotiatedContentResult"获取IActionResult
的内容但在Xunit中不起作用。
所以我想知道如何在Xunit中获取IActionResult
的内容值?
测试代码示例如下:
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中执行此操作吗?
答案 0 :(得分:22)
取决于您期望返回的内容。在前面的示例中,您使用了这样的操作。
[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);
}
}
该方法将返回OkObjectResult
或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);
}