如何解决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 举报,一经查实,本站将立刻删除。