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

.Net 5.0下使用NUnit做Mock测试时Insert方法返回null如何解决?

问题原因

Mock不生效的核心是Moq的参数匹配规则未命中:

  • 你在Setup Insert方法时写的_gameRepository.Setup(x => x.Insert(new Game())).ReturnsAsync(newGame);,这里的参数是测试方法内新创建的Game引用类型实例。
  • 业务代码CreateGame中调用_gameRepository.Insert时,传入的是业务逻辑内部生成的另一个Game实例,两个实例引用地址不同,Moq对引用类型默认按引用匹配,因此找不到对应的Setup规则,返回默认值null。
  • 之前的GetById测试能正常生效,是因为参数为值类型int,Moq对值类型默认按值匹配,Setup时传入的5和调用时传入的5值相等,因此能命中规则。
解决方案

根据测试需求选择以下两种方案即可:

方案1:不需要校验传入Insert的Game参数内容

直接用It.IsAny<Game>()匹配任意Game类型参数:

_gameRepository.Setup(x => x.Insert(It.IsAny<Game>())).ReturnsAsync(newGame);

方案2:需要校验传入Insert的Game参数是否符合业务规则

用It.Is<Game>()添加参数校验逻辑,比如校验生成的随机卡牌值在合法范围:

_gameRepository.Setup(x => x.Insert(It.Is<Game>(g => g.LastDrawedCard >= 1 && g.LastDrawedCard <= 12)))
    .ReturnsAsync(newGame);
额外优化建议

你原测试代码中的断言Assert.IsTrue(newGame.LastDrawedCard > 0);是校验你自己在测试中定义的固定对象的属性,永远为真,没有测试意义,建议修改为校验返回结果:

[Test]
public async Task CreateGame_ShouldReturnNewGameWithLastDrawedCard()
{
    var expectedGame = new Game()
    {
        Id = 5,
        LastDrawedCard = 3
    };
    _gameRepository.Setup(x => x.Insert(It.IsAny<Game>())).ReturnsAsync(expectedGame);
    var newGameResult = await _gameBusiness.CreateGame();
    // 校验返回结果符合预期
    Assert.IsTrue(newGameResult.LastDrawedCard > 0);
    Assert.AreEqual(expectedGame.Id, newGameResult.Id);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 13:54:04