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

如何在NSubstitute中为特定类型或接口设置全局默认返回值?

统一配置NSubstitute替代实例的默认返回值

当然可以,有两种常用方案避免逐个配置替代实例的返回值:

1. 全局默认配置

利用NSubstitute的全局配置能力,一次性指定某类类型或某类返回值的默认行为,后续创建的对应替代实例会自动应用该规则。

针对特定接口的方法配置

如果仅需为ISomeInterface的GetValue()方法统一设置返回值:

// 在测试初始化逻辑(如[SetUp]方法)中执行全局配置
NSubstitute.Configure(config => 
    config.For<ISomeInterface>()
          .ReturnsForAll(method => method.Name == nameof(ISomeInterface.GetValue) 
              ? "TestString" 
              : null)
);

// 后续创建的实例无需单独配置
var mock1 = Substitute.For<ISomeInterface>();
var mock2 = Substitute.For<ISomeInterface>();

// 两个实例的GetValue()都会返回"TestString"
Console.WriteLine(mock1.GetValue()); // 输出 TestString
Console.WriteLine(mock2.GetValue()); // 输出 TestString

针对所有返回string类型的方法配置

如果要让所有返回string类型的方法默认返回"TestString"(替代默认的null),可以用通用规则:

NSubstitute.Configure(config => 
    config.ForAllMethodsReturning<string>().Returns("TestString")
);

// 任意返回string的mock方法都会自动返回"TestString"
var mock = Substitute.For<ISomeInterface>();
var otherMock = Substitute.For<IAnotherInterfaceWithStringReturn>();

2. 封装工厂方法

如果全局配置不够灵活,或仅需在部分测试中应用规则,可封装工厂方法创建预配置的替代实例:

public static class MockFactory
{
    public static ISomeInterface CreateConfiguredSomeInterface()
    {
        var mock = Substitute.For<ISomeInterface>();
        mock.GetValue().Returns("TestString");
        // 可在此添加更多统一配置
        return mock;
    }
}

// 使用时直接调用工厂方法
var mock1 = MockFactory.CreateConfiguredSomeInterface();
var mock2 = MockFactory.CreateConfiguredSomeInterface();

这种方式便于维护,后续修改默认返回值时仅需调整工厂方法即可。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 17:05:57