Nsubstitute拦截硬依赖

时间:2014-10-15 18:29:54

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

我正在测试遗留代码,我正在处理一个实例化另一个类的类。我相信这是可以使用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
    }

1 个答案:

答案 0 :(得分:3)

可以使用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());
相关问题