2017-06-13 103 views
-2
 public interface Interface1 
    { 
     void DoSomething1(int a); 
    } 

    public interface Interface2 
    { 
     void DoSomething2(int a); 
    } 

    public class Class1: Interface1 
    { 
     private Interface2 _interface2; 

     public Class1(Interface2 _interface2) 
     { 
      this._inteface2= _interface2; 
     } 

     public void DoSomething1(int a) 
     { 
      _interface2.DoSomething2(a); 
     } 
    } 

public class Class2: Interface2 
    { 
     public void DoSomething2(int a) 
     { 
      // some action 
     } 
    } 

這是簡化的代碼。 我不知道如何測試Class1是否使用Moq在Class2中調用DoSomething2(int a),在特定的TestCases中使用C#?如何測試一個類中的方法是否使用Moq從另一個類中調用方法?

+3

顯示你有什麼到目前爲止已經試過和你在哪裏具有在困難[MCVE]。這樣一來,它表明了一些努力,試圖找出它,而不僅僅是告訴我如何去做。 – Nkosi

回答

0

如果你要測試的Class1,你應該嘲笑它的依賴,在這種情況下接口2這樣

//First create the mock 
var mocked = new Mock<Interface2>(); 

//then setup how the mocked interface methods should work 
mocked.Setup(a=>a.DoSomething2(It.IsAny<int>()).Returns(null); 

//Add the mocked object to the Class1 constructor 
var class1 = new Class1(mocked.Object); 

//then Act on your class1 which will use your mocked interface 
class1.DoSomething1(1); 
+0

謝謝你,問題出在安裝程序。我沒有使用過「It.IsAny 」 – hurms

+0

@ hurms爲什麼你將我的答案標記爲正確,然後將其刪除?我沒有提供正確的解決方案嗎? –

+0

我不知道。我只是正確地回答了其他的答案,然後它沒有選中我的假設。我的錯。 – hurms

0

由於您正在注入Interface2Class1構造函數,所以您需要使用Moq來模擬它。然後您需要執行DoSomething1並調用Verify方法來確保Interface2的方法被調用一次。如果不是 - 測試將失敗。示例如下:

[TestFixture] 
public class Class1Tests 
{ 
    [Test] 
    public void DoSomething1_DoSomething2IsCalled() 
    { 
     //Setup 
     //create a mock for Class1 dependency 
     var mock = new Mock<Interface2>(); 
     var sut = new Class1(mock.Object); 

     //execute 
     sut.DoSomething1(It.IsAny<int>()); 

     //test 
     mock.Verify(m => m.DoSomething2(It.IsAny<int>()), Times.Once()); 
    } 
} 
+0

請儘量避免將代碼轉儲爲答案,並嘗試解釋它的作用和原因。對於那些沒有相關編碼經驗的人來說,你的代碼可能並不明顯。請編輯你的答案,包括[澄清,上下文,並嘗試提到你的答案中的任何限制,假設或簡化。](https://stackoverflow.com/help/how-to-answer) –

+0

感謝您的反饋@Sam Onela 。思想評論應該足夠了。將更新 – Artem

+0

我使用驗證方法,現在我有另一個問題。 如果我想用錯誤的參數進行測試,所以第二種方法從來沒有被稱爲如何實施第一種方法? 我已經實現了方法,所以它會拋出異常如果參數是錯誤的,所以當我運行單元測試時,它總是拋出一個異常。它從來沒有給我綠燈,第二種方法不被稱爲一次。 使用mocked.Verify(a => a.DoSomething2(a),Times.Never()); 謝謝你的回答。 – hurms

相關問題