You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 11:42:44