2016-10-26 17 views
0

我想在我的C#單元測試程序中使用NSubstitution。在c#中的方法的NSub取代?

我想對mehtod內部調用的方法進行替換。 這裏有一個例子:

public class operation 
{ 
    public int addition(int a, int b) 
    { 
    return (a + b); 
    } 
} 

public class anotherClass 
{ 
    public int increment(int ax, int bx) 
    { 
    operation loc = new operation(); 
    ax = loc.addition(ax,bx); 
    return (ax + 1); 
    } 
} 

是否可以調用增量()方法在我的主要功能和應用替代的加入()方法?

我想在increment()方法中調用addition()方法時強制返回值。例如迫使一個ecxeption投擲。

此外,我無法編輯代碼,因此添加接口實現將不是一個好的解決方案。

+0

請說明您的具體問題或添加額外的細節亮點正是你所需要的。正如目前所寫,很難確切地說出你在問什麼。請參閱如何問問頁面以獲取幫助以澄清此問題。 – mybirthname

+0

我爲目標增加了更多的清晰度。 @mybirthname –

+0

NSubstitute總是返回一個新的對象,你可以重寫這些方法(假設你用一個虛擬方法替代了一個接口或一個類),它不會改變現有的對象或「普通的」.NET對象。既然你正在構建一個新的'操作'在所討論的方法中,你不能改變那個新的對象,你必須首先讓NSubstitute創建它的替代變體,然後你必須把這個方法和讓它使用這個新的對象而不是創建它自己的。 –

回答

0

既然你要創建的operation您正在測試(increment)方法中一個新的實例,有沒有辦法讓NSubstitut來代理您的來電addition - 你最好(有很多原因,一個使用Inversion of control這是可測試性),能夠替代你的功能:

public interface IOperation 
{ 
    int addition(int a, int b); 
} 

public class operation : IOperation 
{ 
    public int addition(int a, int b) 
    { 
    return (a + b); 
    } 
} 

public class anotherClass 
{ 
    private readonly IOperation _operation; 
    public anotherClass(IOperation operation) 
    { 
     _operation = operation; 
    } 

    public int increment(int ax, int bx) 
    {   
    ax = _operation.addition(ax,bx); 
    return (ax + 1); 
    } 
} 

這樣一來,就可以運行應用程序時,通過你的operation類的實例來anotherClass,並通過在單元測試中的NSubstitute.Substitute.For<IOperation>()。然後,您可以使用模擬得到它返回任何你想要的:

var mockOperation = NSubstitute.Substitute.For<IOperation>(); 
mockOperation.addition(Arg.Any<int>(), Arg.Any<int>()).Return(/*...*/); 
+0

因此,簡而言之,如果我無法更改我正在測試的代碼(添加接口),那麼這是不可能的? –

+0

@AngeloCharl我無法想象如何在不改變代碼的情況下做到這一點 - 如果這些類在不同的程序集中,那麼您可能會去操作'operation'並引用它來代替原始程序集,但即使這樣太混亂了tbh – KMoussa

0

要做到這一點,你必須傳遞給anotherClass依賴於操作類。你可以用不同的方式做到這一點,其中之一是使用構造函數注入它,但首先你必須添加IOperation接口,以便能夠使用NSubstitute模擬它。示例代碼可能看起來像:

public interface Ioperation 
     { 
      int addition(int a, int b); 
     } 

     public class operation : Ioperation 
     { 
      public int addition(int a, int b) 
      { 
       return (a + b); 
      } 
     } 

     public class anotherClass 
     { 

      Ioperation _operation; 
      public anotherClass(Ioperation operation) 
      { 
       _operation = operation; 
      } 

      public int increment(int ax, int bx) 
      { 
       operation loc = new operation(); 
       ax = loc.addition(ax, bx); 
       return (ax + 1); 
      } 
     } 

然後,您可以按以下方式嘲笑它NSubstitute:

operation.addition(Arg.Any<int>(), Arg.Any<int>()).Throws(new Exception()); 

,並通過構造函數傳遞