C# 如何测试IActionResult及其内容

C# 如何测试IActionResult及其内容,c#,unit-testing,asp.net-core,nunit,C#,Unit Testing,Asp.net Core,Nunit,我正在用C#和.NETCore2.0开发一个ASP.NETCore2WebAPI 我更改了一个方法,将其添加到try-catch中,以允许我返回状态代码 public IEnumerable<GS1AIPresentation> Get() { return _context .GS1AI .Select(g => _mapper.CreatePresentation(g)) .ToList(); } 但是现在我的测试方

我正在用C#和.NETCore2.0开发一个ASP.NETCore2WebAPI

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

public IEnumerable<GS1AIPresentation> Get()
{
    return _context
        .GS1AI
        .Select(g => _mapper.CreatePresentation(g))
        .ToList();
}
但是现在我的测试方法有一个问题,因为现在它返回的是
IActionResult
,而不是
IEnumerable

或者我可以在
IActionResult

中获取
IEnumerable
,在控制器中调用的
返回Ok(…)
返回a,它是从
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());
}
[测试]
public void应返回GS1可用(){
//安排
MockGS1(mockContext,gs1Data);
var controller=new GS1AIController(mockContext.Object、mockMapper.Object);
//表演
IActionResult=controller.Get();
//断言
var okObjectResult=结果为okObjectResult;
Assert.IsNotNull(okObjectResult);
var presentations=okObjectResult.Value作为IEnumerable;
Assert.IsNotNull(演示文稿);
Assert.AreEqual(presentations.Select(g=>g.Id).Intersect(gs1Data.Select(d=>d.Id)).Count(),
Count());
}
参考文献

[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());
}
return _context
    .GS1AI
    .Select(g => _mapper.CreatePresentation(g))
    .ToList();
[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());
}