2017-09-01 58 views
3

我正在嘗試使用Moq爲特定接口編寫一些測試。實現接口的對象的值由我們在這個問題中稱爲「controller」的類來設置。如何從Moq獲得的模擬界面獲得價值?

接口:

public interface ITestInterface 
{ 
    int number {set;} 
} 

我的模擬:

Mock<ITestInterface> myTestMock = new Mock<ITestInterface>(); 

做測試,我希望控制器設置在嘲笑類的數量,但後來我需要得到值來測試它。事情是這樣的:

Controller c = new Controller(myTestMock.Object); 
c.Initialize(); //initialization will set number to something 
Assert.AreEqual(myTestMock.number, 3); 

當然,我得到一個錯誤,因爲我無法讀取該值,因爲該接口沒有一個「get」方法。

如何在不更改界面的情況下爲我的模擬設置獲取?

+1

相反Assert.AreEqual'的',也許你可以用'myTestMock.VerifySet(X => x.number = 3);' –

+0

@ThariqNugrohotomo它會給我同樣的錯誤「缺少獲取訪問者」 – Th0rndike

+2

@ Th0rndike - 刪除'Assert'行。 @Thariq是正確的'myTestMock.VerifySet(x => x.number = 3);'工作。 (剛剛測試過,因爲它對我來說也是新的)。 - 假設'c.Initialize();'*真*設置數字。我甚至嘗試過'myTestMock.VerifySet(x => x.number = 4);'並且測試失敗,因爲它只認識到它被設置爲3,而不是4. – Corak

回答

0

使用自己的實現

public class FakeTestInterface : ITestInterface 
{ 
    public int NumberValue { get; private set; } 
    public int number 
    { 
     set 
     { 
      NumberValue = value; 
     } 
    } 
} 

然後在測試

var testMock = new FakeTestInterface(); 
var controller = new Controller(testMock); 
controller.Initialize(); 
Assert.AreEqual(testMock.NumberValue, 3); 

所有嘲弄框架的設計,使我們的生活更輕鬆,因爲我們並不需要編寫自己的「假」的實施。
當你面臨着嘲諷框架問題 - 寫自己的模仿對象