微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

XUnit + Moq + FluentAssertions,检查 Task 上的 null 而不是正确的对象

如何解决XUnit + Moq + FluentAssertions,检查 Task 上的 null 而不是正确的对象

我是单元测试和最小起订量的新手。

使用 Postman 测试 DeleteItemAsync(),

    [HttpDelete("{id:length(24)}")]
    public async Task<IActionResult> DeleteItemAsync(string id)
    {
        var item = _ItemRepo.GetItemByIdAsync(id);
        if (item == null)
            return NotFound();
        await _itemRepo.DeleteItemAsync(id);
        return NoContent();
    }

当未找到该项目时,我会得到正确的结果 NotFound。

运行我的单元测试时它失败了,因为在控制器中,它正在检查由 moq _repoStub 调用 GetItemByIdAsync(id) 返回的 Task 对象上的 null。

    [Fact]
    public async Task DeleteItemAsync_ItemDoesntExist_ReturnsNotFound()
    {
        // Arrange
        _repoStub
            .Setup(repo => repo.GetItemByIdAsync(It.IsAny<String>()))
            .ReturnsAsync((Item)null);
        _repoStub
            .SetupSequence(repo => repo.DeleteItemAsync(It.IsAny<String>()))
            .Returns(Task.Fromresult<NotFoundResult>(null));

        var controller = new ItemController(_repoStub.Object,_mapperStub);

        // Act
        var actionResult = await controller.DeleteItemAsync(It.IsAny<String>());

        // Assert
        actionResult.Should().BeOfType<NotFoundResult>();
    }

解决方法

GetItemByIdAsync 应该在被测对象中等待

[HttpDelete("{id:length(24)}")]
public async Task<IActionResult> DeleteItemAsync(string id)
{
    var item =  await _ItemRepo.GetItemByIdAsync(id); //<--!!!
    if (item == null)
        return NotFound();
    await _itemRepo.DeleteItemAsync(id);
    return NoContent();
}

否则它将返回 Task,因此不会像您的错误所示那样为 null

另外,请注意 It.IsAny 应该只用于期望表达式而不是变量

[Fact]
public async Task DeleteItemAsync_ItemDoesntExist_ReturnsNotFound()
{
    // Arrange
    _repoStub
        .Setup(repo => repo.GetItemByIdAsync(It.IsAny<String>()))
        .ReturnsAsync((Item)null);
    _repoStub
        .SetupSequence(repo => repo.DeleteItemAsync(It.IsAny<String>()))
        .Returns(Task.FromResult<NotFoundResult>(null));

    var controller = new ItemController(_repoStub.Object,_mapperStub);

    // Act
    var actionResult = await controller.DeleteItemAsync(""); //<--It.IsAny<String>() removed

    // Assert
    actionResult.Should().BeOfType<NotFoundResult>();
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?