NSubstitute已配置方法调用始终返回Null问题排查求助
问题根因
你的代码核心问题是混用了Moq的参数匹配器和NSubstitute的配置逻辑,导致工厂方法的返回配置未生效,具体原因如下:
- NSubstitute仅能识别自身提供的参数匹配器
Arg.Any<T>(),你代码中导入了Moq命名空间,配置factory.CreateInService返回规则时使用了Moq的It.IsAny<int>()匹配器,NSubstitute无法识别该规则,因此调用factory.CreateInService(100)时没有命中配置,默认返回了null,后续调用null对象的GetName方法自然返回默认的(null, null)空元组。 - 你对
myService.GetName的配置同时使用了参数匹配器和ReturnsForAnyArgs,属于冗余配置,保留任意一种即可。
修正后代码
using NSubstitute; using Xunit; namespace ConsoleApp1 { public interface IFactory { IMyService CreateInService(int number); } public interface IMyService { (Status?, Status?) GetName(string name); } public enum Status { UnKnown = 0, } public class TupleTest { [Fact] public void GetTupleTest() { (Status?, Status?) exceptedStatusTuple = (Status.UnKnown, Status.UnKnown); var factory = Substitute.For<IFactory>(); var myService = Substitute.For<IMyService>(); // 将Moq的It.IsAny替换为NSubstitute的Arg.Any factory.CreateInService(Arg.Any<int>()).Returns(myService); // 去掉冗余的参数匹配器,直接用ReturnsForAnyArgs即可 myService.GetName(default).ReturnsForAnyArgs(exceptedStatusTuple); var result = factory.CreateInService(100).GetName("test"); Assert.Equal(result.Item1, exceptedStatusTuple.Item1); Assert.Equal(result.Item2, exceptedStatusTuple.Item2); } } }
修改后运行测试即可正常通过。
内容的提问来源于stack exchange,提问作者AdvancingEnemy
相关产品推荐
相关产品推荐

