简体   繁体   中英

How to test IActionResult and its content

I'm developing an ASP.NET Core 2 web api with C# and .NET Core 2.0.

I have changed a method to add it the try-catch to allow me return status codes.

public IEnumerable<GS1AIPresentation> Get()
{
    return _context
        .GS1AI
        .Select(g => _mapper.CreatePresentation(g))
        .ToList();
}

Changed to:

public IActionResult Get()
{
    try
    {
        return Ok(_context
            .GS1AI
            .Select(g => _mapper.CreatePresentation(g))
            .ToList());
    }
    catch (Exception)
    {
        return StatusCode(500);
    }
}

But now I have a problem in my Test method because now it returns an IActionResult instead of a IEnumerable<GS1AIPresentation> :

[Test]
public void ShouldReturnGS1Available()
{
    // Arrange
    MockGS1(mockContext, gs1Data);

    GS1AIController controller =
        new GS1AIController(mockContext.Object, mockMapper.Object);

    // Act
    IEnumerable<Models.GS1AIPresentation> presentations = controller.Get();

    // Arrange
    Assert.AreEqual(presentations.Select(g => g.Id).Intersect(gs1Data.Select(d => d.Id)).Count(),
                    presentations.Count());
}

My problem is here: IEnumerable<Models.GS1AIPresentation> presentations = controller.Get(); .

Do I need to do refactor an create a new method to test the Select ?

This select:

return _context
    .GS1AI
    .Select(g => _mapper.CreatePresentation(g))
    .ToList();

Or maybe I can get the IEnumerable<Models.GS1AIPresentation> in the IActionResult

The return Ok(...) called in the controller is returning a OkObjectResult , which is derived from IActionResult so you would need to cast to that type and then access the value within.

[Test]
public void ShouldReturnGS1Available() {
    // Arrange
    MockGS1(mockContext, gs1Data);

    var controller = new GS1AIController(mockContext.Object, mockMapper.Object);

    // Act
    IActionResult result = controller.Get();        

    // Assert
    var okObjectResult = result as OkObjectResult;
    Assert.IsNotNull(okObjectResult);
    var presentations = okObjectResult.Value as IEnumerable<Models.GS1AIPresentation>;
    Assert.IsNotNull(presentations);
    Assert.AreEqual(presentations.Select(g => g.Id).Intersect(gs1Data.Select(d => d.Id)).Count(),
                    presentations.Count());
}

Reference Asp.Net Core Action Results Explained

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