.NET Core 6.0:xUnit测试失败,返回NotFoundResult而非NoContentResult
.NET Core 6.0 Web API DeleteComment测试返回NotFound问题
我在开发.NET Core 6.0 Web API时,实现了DeleteComment接口方法,并编写了对应的单元测试。但运行测试时,预期返回NoContentResult,实际却返回NotFoundResult。用Postman和断点以相同ID测试API时功能正常,想排查代码是否存在错误。
测试方法
[Fact] public void DeleteComment_WithValidId_ReturnsNoContentResult() { var commentId = 1; var result = _controller.DeleteComment(commentId); Assert.IsType<NoContentResult>(result); _mockCommentService.Verify(service => service.DeleteComment(commentId), Times.Once); }
API控制器Delete方法
// DELETE: api/Comments/5 [HttpDelete("{id}")] public IActionResult DeleteComment(int id) { var deletingComment = _commentService.GetComment(id); if (deletingComment == null) { return NotFound(); } _commentService.DeleteComment(id); return NoContent(); }
服务层获取评论方法
public Comment GetComment(int id) { return _comments.FirstOrDefault(comment => comment.Id == id); }
服务层删除评论方法
public void DeleteComment(int id) { var commentToDelete = _comments.FirstOrDefault(comment => comment.Id == id); if (commentToDelete != null) { _comments.Remove(commentToDelete); } }
测试失败输出
Assert.IsType() Failure Expected: Microsoft.AspNetCore.Mvc.NoContentResult Actual: Microsoft.AspNetCore.Mvc.NotFoundResult
问题分析与解决
问题出在单元测试的Mock配置上:你只验证了DeleteComment方法的调用,但没有给_mockCommentService的GetComment方法配置返回值。Mock对象默认会返回引用类型的null,所以控制器执行_commentService.GetComment(id)时得到null,直接进入NotFound分支,返回NotFoundResult。
而Postman测试时用的是真实的服务实例,_comments集合中存在ID为1的评论,所以GetComment能返回有效对象,流程正常走到NoContent。
修改测试方法,添加对GetComment的模拟配置即可解决:
[Fact] public void DeleteComment_WithValidId_ReturnsNoContentResult() { var commentId = 1; // 模拟GetComment返回有效评论 _mockCommentService.Setup(service => service.GetComment(commentId)) .Returns(new Comment { Id = commentId }); var result = _controller.DeleteComment(commentId); Assert.IsType<NoContentResult>(result); _mockCommentService.Verify(service => service.DeleteComment(commentId), Times.Once); }
内容的提问来源于stack exchange,提问作者Aisa Asghari
相关产品推荐
相关产品推荐

