2014-10-15 4 views
2

레거시 코드를 단위 테스트하고 다른 클래스를 인스턴스화하는 클래스를 다루고 있습니다. 나는 이것이 MS Fakes를 사용하여 테스트 할 수 있다고 믿지만, NS substitute가 기능을 갖고 있는지 궁금해하고있다. 나는 그 대답이 '아니오'라고 믿지만 확신 할 필요가있다. 다만 기본 코드는 기본 클래스가 호출되어야 함을 지정하여 호출 할 수 없습니다 있는지 확인하십시오 :Nsubstitute intercept 하드 종속성

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 
    } 

답변

3

partial substitution를 사용하여 클래스에서 가상 메소드를 오버라이드 (override) 할 수

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());