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

.NET Core 6中Moq与xUnit测试依赖注入返回null的解决方法

解决单元测试返回null的问题

核心问题:异步测试方法错误使用async void

xUnit不支持async void类型的测试方法,这类方法会在异步操作完成前就结束测试流程,导致你的await jokeController.Get()还没执行完就进入断言环节,最终得到null结果。

修复步骤

  1. 将测试方法的返回类型从async void改为async Task
  2. 确保Mock的Setup逻辑正确(你的现有Setup是没问题的,但配合修复后的方法才能生效)

修改后的测试代码:

public class UnitTest1
{
    private readonly Mock<IDadJokeService> _dadJokeService;
    public UnitTest1()
    {
        _dadJokeService = new Mock<IDadJokeService>();
    }

    // 把async void改成async Task
    public async Task GetDadJoke()
    {
        // Arrange
        var jokeController = new JokeController(_dadJokeService.Object);
        this._dadJokeService.Setup(c => c.GetJokeAsync()).ReturnsAsync(GetDadJokesData());
        // Act
        var result = await jokeController.Get();

        // Assert
        Assert.NotNull(result);
        // 可额外断言返回内容是否符合预期
        Assert.Equal("Success!", result.Message);
        Assert.Equal(200, result.StatusCode);
    }

    private JokeResponseViewModel GetDadJokesData()
    {
        return new JokeResponseViewModel
        {
            id= "218xkq49prc",
            joke = "A termite walks into a bar and asks “Is the bar tender here?”",
            status = 200
        };
    }
}

额外验证点

确认GenericResponseModel和ApiResponse方法的实现逻辑,确保当传入有效的JokeResponseViewModel时,不会返回null的GenericResponseModel。从你的控制器代码来看,只要服务返回的response.status是200,就会调用ApiResponse(response, ...),这个方法应该返回非null实例。

内容的提问来源于stack exchange,提问作者Muhammad Kamran

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 17:58:21