编程语言
首页 > 编程语言> > CodeGo.net>如何在ASP.NET Core项目中使用MStest测试Ok()结果

CodeGo.net>如何在ASP.NET Core项目中使用MStest测试Ok()结果

作者:互联网

我正在使用MStest来测试我的控制器.

我要测试此操作:

[HttpGet(Name = "GetGroups")]
public async Task<IActionResult> Get()
{
    var groups = await _unitOfWork.Repository<Groupe>().GetAllAsync();
    var groupsDto = Mapper.Map<IEnumerable<GroupDto>>(groups);
    if (groupsDto.Count() == 0)
    {
        return NotFound();
    }
    return Ok(groupsDto);
}

此操作的测试之一如下所示:

[TestMethod]
public async Task Group_Get_Should_Return_InstanceOfTypeOkNegotiatedContentResultIEnumerableGroupDto()
{
    // Arrange
    moqGroupRepository.Setup(g => g.GetAllAsync(null)).ReturnsAsync(groups).Verifiable();
    moqUnitOfWork.Setup(x => x.Repository<Groupe>()).Returns(moqGroupRepository.Object);

    var controller = new GroupController(moqUnitOfWork.Object);

    // Act
    var actionResult = await controller.Get() as OkNegotiatedContentResult<IEnumerable<GroupDto>>;

    // Assert
    Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult<IEnumerable<GroupDto>>));
}

这里的问题是ASP.Net Core项目测试中不知道OkNegotiatedContentResult.

我应该使用什么来测试Ok()结果?

解决方法:

The probleme here is OkNegotiatedContentResult is unknow in asp net
core project test What should i use to test Ok() result?

您可以通过安装Microsoft.AspNetCore.Mvc NuGet程序包(定义了IActionResult的实现)来解决此问题.

但是,ASP.NET Core不包含OkNegotiatedContentResult类型,它来自ASP.NET Web API.在ASP.NET Core Controller.Ok()方法中,返回OkObjectResult类型的实例.

您在这两个语句中的检查也不一致:

var actionResult = await controller.Get() as OkNegotiatedContentResult<IEnumerable<GroupDto>>;
Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult<IEnumerable<GroupDto>>));

如果无法将对象强制转换为请求的类型,则as运算符将返回null.因此,您可以将第二张支票替换为以下内容:

Assert.IsNotNull(actionResult);

因此,所需步骤为:

>将Microsoft.AspNetCore.Mvc NuGet软件包安装到Test项目.
>通过以下方式调整测试代码:

// ...
using Microsoft.AspNetCore.Mvc;

[TestMethod]
public async Task Group_Get_Should_Return_InstanceOfTypeOkNegotiatedContentResultIEnumerableGroupDto()
{
    // Arrange
    moqGroupRepository.Setup(g => g.GetAllAsync(null)).ReturnsAsync(groups).Verifiable();
    moqUnitOfWork.Setup(x => x.Repository<Groupe>()).Returns(moqGroupRepository.Object);

    var controller = new GroupController(moqUnitOfWork.Object);

    // Act
    var actionResult = await controller.Get() as OkObjectResult;

    // Assert
    Assert.IsNotNull(actionResult);
    Assert.IsInstanceOfType(actionResult.Value, typeof(IEnumerable<GroupDto>));
}

标签:unit-testing,mstest,visual-studio-2017,asp-net-core-2-0,c
来源: https://codeday.me/bug/20191025/1927345.html