【问题标题】:Nsubstitute intercept hard dependencyNsubstitute 拦截硬依赖
【发布时间】:2014-10-15 18:29:54
【问题描述】:

我正在对遗留代码进行单元测试,并且我正在处理一个实例化另一个类的类。我相信这可以使用 Microsoft Fakes 进行测试,但我想知道 NSubstitute 是否有能力。我相信答案是否定的,但需要确定。

    public class ClassA
    {
        public int MethodA()
        {
            int reportId = this.MethodB();
            return reportId;
        }
        public virtual int MethodB()
        {
            ClassC c = new ClassC();
            return c.MethodA();
        }
    }

   public class ClassC
   {
       public virtual int MethodA()
       {
        return 2;
       }
   }
    [Test]
    public void Test_ClassA()
    {
        ClassA subclassA = new ClassA();
        var subclassC = Substitute.For<ClassC>();  //this is pointless the way I have it here
        subclassC.MethodA().Returns(1);            //this is pointless the way I have it here
        int outValue = subclassA.MethodA();
        Assert.AreEqual(outValue, 1);  //outvalue is 2 but I would like it to be 1 if possible using Nsubstitute
    }

【问题讨论】:

    标签: unit-testing nsubstitute tightly-coupled-code


    【解决方案1】:

    可以使用partial substitution覆盖类中的虚方法:只需通过指定不能调用基类来确保不能调用基代码:

    var A = Substitute.ForPartsOf<ClassA>();
    var C = Substitute.ForPartsOf<ClassC>();
    
    C.When(c => c.MethodA()).DoNotCallBase();
    C.MethodA().Returns(10);
    A.When(a => a.MethodB()).DoNotCallBase();
    var cResult = C.MethodA();
    A.MethodB().Returns(cResult);
    
    Console.WriteLine(A.MethodB());
    Console.WriteLine(C.MethodA());
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2018-01-30
      • 2014-03-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多