如何测试IActionResult及其内容 [英] How to test IActionResult and its content

查看:396
本文介绍了如何测试IActionResult及其内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用C#和.NET Core 2.0开发ASP.NET Core 2 Web API.

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

我已经更改了将try-catch添加到其中的方法,以允许我返回状态代码.

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

更改为:

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

但是现在我的Test方法遇到了问题,因为它现在返回了IActionResult而不是IEnumerable<GS1AIPresentation>:

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

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

我需要重构一个新方法来测试Select吗?

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

此选择:

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

或者也许我可以在IActionResult

推荐答案

在控制器中调用的return Ok(...)返回

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

参考 Asp.Net核心操作结果已解释

这篇关于如何测试IActionResult及其内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆