简体   繁体   English

在XUnit中如何对收到的IActionResult进行解析

[英]In XUnit how to do parsing on IActionResult you receive

How do I parse the IActionResult I received in my XUnit Test. 如何解析在IActionResult测试中收到的IActionResult

I have tried the below and getting error in the line (returning null ) 我已经尝试了以下内容并在行中出现错误(返回null

var okObjectResult = actionResult as OkObjectResult;

Controller Class 控制器类

public IActionResult Details(int id)
{
    var pie = _pieRepository.GetPieById(id);

    if(pie==null)
    {
        return NotFound();
    }
    else
    {
        return View(pie);
    }          
}

XUnit Test Case 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);
}

I have referred the code from the below post and still no luck " How to get content value in Xunit when result returned in IActionResult type " 我已经从下面的帖子中引用了代码,但仍然没有运气“ 当IActionResult类型返回结果时如何在Xunit中获取内容值

OkObjectResult usually returned by API controllers. OkObjectResult通常由API控制器返回。 In your particular case controller returns ViewResult type. 在您的特定情况下,控制器返回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);

Test controller logic in ASP.NET Core 在ASP.NET Core中测试控制器逻辑

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

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