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

如何在单元测试中判断注入的IInjectedService是否被调用?

验证依赖服务是否被调用的实现方案

完全可以实现这个验证需求,以下是基于主流Mock框架的具体实现示例:

使用Moq框架的示例

using Moq;
using Xunit;

public class MyServiceTests
{
    [Fact]
    public void Method1_ShouldCallGenerateOnInjectedService()
    {
        // 创建IInjectedService的Mock实例
        var injectedServiceMock = new Mock<IInjectedService>();
        
        // 实例化MyService并传入Mock对象
        var myService = new MyService(injectedServiceMock.Object);
        
        // 调用待测试的Method1
        myService.Method1(123);
        
        // 验证Generate方法是否被调用过至少一次
        injectedServiceMock.Verify(s => s.Generate(), Times.Once);
    }
}

使用NSubstitute框架的示例

using NSubstitute;
using Xunit;

public class MyServiceTests
{
    [Fact]
    public void Method1_ShouldCallGenerateOnInjectedService()
    {
        // 创建IInjectedService的替代实例
        var injectedService = Substitute.For<IInjectedService>();
        
        // 实例化MyService
        var myService = new MyService(injectedService);
        
        // 调用Method1
        myService.Method1(456);
        
        // 验证Generate方法是否被调用
        injectedService.Received().Generate();
        // 若需指定调用次数,可改为 injectedService.Received(1).Generate()
    }
}

额外注意事项

  • 先通过NuGet安装对应的Mock框架(Moq/NSubstitute)及测试框架(如xUnit、NUnit)
  • 可以精准控制调用次数验证:比如Moq的Times.Never验证方法未被调用,Times.Exactly(2)验证调用两次;NSubstitute则用Received(n)实现相同逻辑
  • 如果Generate方法带参数,验证时需匹配参数,例如s => s.Generate("target"),或用It.IsAny<string>()匹配任意参数

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 14:54:52