2016-11-10 69 views
0

我對Nsubstitute和單元測試相當陌生。 我知道在單元測試中,你不關心任何其他的依賴關係。所以爲了應用這個規則,我們模擬單位。Nsubstitute:嘲笑一個對象單元測試的參數

我有這樣的例子進行測試的代碼,其中一個方法有一個對象參數:

class dependency { 
    public int A; 
    public dependency() { 
    // algorithms going on ... 
    A = algorithm_output; 
    } 
} 

class toTest { 
    public int Xa; 
    public void Foo(dependency dep_input){ 
    Xa = dep_input.A; 
    // Xa will be used in an algorithm ... 
    } 
} 

我想嘲弄的構造,但我無法弄清楚如何Nsubstitute。所以最終,我會如何測試這個?

+0

您只能用NSubstitute模擬接口和虛擬方法。構造函數是不可行的,因爲非虛擬或靜態方法。也許你應該爲你的班級添加一個界面? –

+0

如果你想測試這個接口,你可能想要使用一個接口。如果您仍然對實際類有依賴關係,那麼您可能仍會在該類中運行可能影響您測試的代碼,並且您可能不得不圍繞該類中的某些行爲進行提示,以使其適合您的測試。 。 –

+0

如果我無法更改要測試的代碼(出於某種原因,在我正在進行的項目中),該怎麼辦? @ LasseV.Karlsen –

回答

4

我不能添加評論,因爲它太長了,所以我添加一個答案: 如果你想測試Foo你不需要模仿ctor而是dep_input。例如,如果您使用Moq。但是您也可以使用存根

public interface IDependency 
{ 
    int A { get; } 
} 

public class Dependency : IDependency 
{ 
    public int A { get; private set; } 

    public Dependency() 
    { 
     // algorithms going on ... 
     A = algorithm_output(); 
    } 

    private static int algorithm_output() 
    { 
     return 42; 
    } 
} 

public class ToTest 
{ 
    public int Xa; 

    public void Foo(IDependency dep_input) 
    { 
     Xa = dep_input.A; 
     // Xa will be used in an algorithm ... 
    } 
} 

[TestFixture] 
public class TestClass 
{ 
    [Test] 
    public void TestWithMoq() 
    { 
     var dependecyMock = new Mock<IDependency>(); 
     dependecyMock.Setup(d => d.A).Returns(23); 

     var toTest = new ToTest(); 
     toTest.Foo(dependecyMock.Object); 

     Assert.AreEqual(23, toTest.Xa); 
     dependecyMock.Verify(d => d.A, Times.Once); 
    } 

    [Test] 
    public void TestWithStub() 
    { 
     var dependecyStub = new DependencyTest(); 

     var toTest = new ToTest(); 
     toTest.Foo(dependecyStub); 

     Assert.AreEqual(23, toTest.Xa); 
    } 

    internal class DependencyTest : IDependency 
    { 
     public int A 
     { 
      get 
      { 
       return 23; 
      } 
     } 
    } 
} 
+0

啊!這是一個非常有用的例子。謝謝! @Dominik –