2013-03-08 59 views
2

嘲弄的方法我寫,執行邏輯下一個單元測試:生成存根或.NET

SomeObject obj1 = new SomeObject(); 
obj1.SomeMethod(args); 

SomeMethod

public void SomeMethod(*Some Args*){  
    AnotherObject obj2 = new AnotherObject(); 
    Obj2.OtherMethod(); 
} 

在我的測試中我不關心Obj2.OtherMethod()實際上做了什麼,我希望測試忽略它。所以我認爲生成一個存根會爲我修復它,但我不知道如何去做。

+1

你有沒有看過Moq或RhinoMocks?這聽起來像你想嘲笑Obj2。 – Jamie 2013-03-08 14:31:31

回答

3

下面是一種方法。如果你有一個AnotherObject實現的接口(比如說IAnother,至少AnotherMethod作爲一個方法),你的正常執行路徑會將AnotherObject的一個實例傳遞給SomeMethod。

然後進行測試,您可以傳遞一個實現IAnother接口的模擬對象 - 通過使用模擬框架或自己編碼。

所以你必須:

Public void SomeMethod(IAnother anotherObject) 
{  
    anotherObbject.OtherMethod(); 
} 
測試

Public class MyMock : IAnother... 

-

IAnother another = new MyMock(); 
..SomeMethod(myMock) 

,但在真正的代碼

IAnother = new AnotherObject()... 

你明白了。