如何解析在XUnit测试中收到的IActionResult
。
我尝试了以下操作,并在该行中出错(返回 null )
var okObjectResult = actionResult as OkObjectResult;
控制器类
public IActionResult Details(int id)
{
var pie = _pieRepository.GetPieById(id);
if(pie==null)
{
return NotFound();
}
else
{
return View(pie);
}
}
XUnit测试用例
[Fact]
public async void DetailsTest()
{
MockPieRepository _data = new MockPieRepository();
int _id = 1;
string desc = "Selenium Pie";
var homecontroller = new HomeController(_data);
IActionResult actionResult = homecontroller.Details(_id);
var okObjectResult = actionResult as OkObjectResult;
Assert.NotNull(okObjectResult);
var model = okObjectResult.Value as Pie;
Assert.NotNull(model);
Assert.Equal(1, model.Id);
Assert.Equal(desc, model.ShortDescription);
}
我已经引用了以下帖子中的代码,但仍然没有运气“ How to get content value in Xunit when result returned in IActionResult type”
答案 0 :(得分:2)
OkObjectResult
通常由API控制器返回。在您的特定情况下,控制器返回ViewResult
类型。
var actionResult = homecontroller.Details(_id);
var viewResult = actionResult as ViewResult;
var actualPie = viewResult.ViewData.Model as Pie;
Assert.NotNull(model);
Assert.Equal(1, model.Id);
Assert.Equal(desc, model.ShortDescription);