问题

我是单元测试控制器逻辑.我有一个控制器操作,它采用字符串参数,如下所示:

 public async Task<IActionResult> Get(string searchCriterion)
{
    if (string.IsNullOrEmpty(searchCriterion))
    {
        // Log modelstate errors
        return BadRequest("Hello");
    }

    // etc...
}
 

请注意检查string.IsNullOrEmpty(searchCriterion)的警卫.

在我的单元测试中,我喜欢使用It.IsAny<string>():

 // Act
var result = await controller.GetSearchNetworkAsync(It.IsAny<string>());
 

警卫意味着我不能使用它,因为It.IsAny<string>()意味着测试字符串确实可以通过null ot空.

我的问题是:我可以在我的单元测试中传递对应于“除null或空之外的任何字符串值”的参数吗?

编辑

请找到完整的单元测试...

     [Fact]
    public async Task GetSearchNetworkAsync_ReturnsOkWithNetworkListViewModelCollection_Rn()
    {
        // Arrange
        var mockRepo = new Mock<IUserRepository>();
        mockRepo.Setup(repo => repo.GetUserAndNetworkAsync(It.IsAny<string>()))
             .ReturnsAsync(GetOwnUserProfile());
        mockRepo.Setup(repo => repo.SearchBirdersToFollowAsync(It.IsAny<ApplicationUser>(), It.IsAny<string>(), It.IsAny<IEnumerable<string>>()))
            .ReturnsAsync(GetListOfApplicationUsers(3));

        var mockUnitOfWork = new Mock<IUnitOfWork>();

        var controller = new UserController(_mapper, mockUnitOfWork.Object, _logger.Object, mockRepo.Object);

        controller.ControllerContext = new ControllerContext()
        {
            HttpContext = new DefaultHttpContext() { User = GetTestClaimsPrincipal() }
        };

        // Act
        //var result = await controller.GetSearchNetworkAsync(It.IsAny<string>());
        var result = await controller.GetSearchNetworkAsync(It.Is<string>(str => !string.IsNullOrEmpty(str)));

        // Assert
        var objectResult = result as ObjectResult;
        Assert.NotNull(objectResult);
        Assert.IsType<OkObjectResult>(result);
        Assert.True(objectResult is OkObjectResult);
        Assert.Equal(StatusCodes.Status200OK, objectResult.StatusCode);
        Assert.IsType<List<NetworkUserViewModel>>(objectResult.Value);

        var model = objectResult.Value as List<NetworkUserViewModel>;
        Assert.Equal(3, model.Count);
    }
 

  最佳答案

It.IsAny<string>()意在仅作为mocks设置的一部分使用.

 mock.Setup(_ => _.SomeMember(It.IsAny<string>()).Returns(SomeValue);
 

它不意味着在Setup表达式之外使用,并将返回提供的通用参数的默认值。

IE

 It.IsAny<string>() == null
 

使用实际的字符串将所需的值传递给测试中的主题。

 //Arrange

//...

string searchCriterion = "Any String You Want Here";

// Act
var result = await controller.GetSearchNetworkAsync(searchCriterion);
 

  相同标签的其他问题

c#.net-corexunit.net
上一个问题:
下一个问题: