如何测试IActionResult及其内容

时间:2018-01-15 13:35:47

标签: c# unit-testing asp.net-core nunit

我正在使用C#和.NET Core 2.0开发ASP.NET Core 2 web api。

我已经更改了一个方法来添加try-catch以允许我返回状态代码。

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

更改为:

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

但是现在我的Test方法存在问题,因为它现在返回IActionResult而不是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());
}

我的问题在于:IEnumerable<Models.GS1AIPresentation> presentations = controller.Get();

我是否需要重构一个新方法来测试Select

此选择:

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

或者我可以在IEnumerable<Models.GS1AIPresentation>

中获得IActionResult

1 个答案:

答案 0 :(得分:6)

控制器中调用的return Ok(...)返回OkObjectResult,该Asp.Net Core Action Results Explained派生自IActionResult,因此您需要转换为该类型,然后访问其中的值。

[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());
}

参考https://github.com/vrld/hump/blob/master/vector.lua