xUnit调用因模拟行为严格而失败

时间:2018-10-18 03:12:04

标签: c# unit-testing .net-core xunit

使用xUnit对代码编写测试时,我遇到了错误。在该测试中,我尝试使用workerExist(İf是否存在任何用户),但是在测试中,当我创建操作结果属于metot时,我接受了调用失败,并出现模拟行为严格错误。我找不到解决方法

public async Task<IActionResult> EditUser([FromBody] UserDto userDto)
    {
        if (!ModelState.IsValid)
            return BadRequest(ModelState);

        var workerExist = _user.GetUserById(UserDto.userID);

        if (workerExist == null)
            return NotFound();

        var worker = new Workers
        {
            username = userDto.Username
        };

        await _workers.EditWorker(worker);

        return Ok(worker);
    }


public async Task EditUser_Should_Call_GetUserById_And_Return_NotFound_If_Returns_Null()
    {
        UserControllerMock mock = UserControllerMock.Create();
        mock.UserService.Setup(service => service.GetUserById(It.IsAny<int>())).ReturnsAsync(() => null);

        IActionResult actionresult = await mock.EditUser(new UserDto());
        var notFoundResult = actionresult as NotFoundResult;

        Assert.NotNull(notFoundResult);
        mock.UserService.Verify(service => service.GetUserById(It.IsAny<int>()), Times.Once);
    }

0 个答案:

没有答案