简体   繁体   中英

In XUnit how to do parsing on IActionResult you receive

How do I parse the IActionResult I received in my XUnit Test.

I have tried the below and getting error in the line (returning 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

[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 "

OkObjectResult usually returned by API controllers. In your particular case controller returns ViewResult type.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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