2013-03-01 511 views
1

請看看下面的代碼單元測試調用另一個類的方法的方法

int sum(int a, int b) 
{ 
    int x = memberInstance.xyz(a); // memberInstance is an object of another class 
    ..... 
    ..... 
} 

說,它也被稱爲是1-10之間XYZ方法返回的數字。 現在,我想開發sum方法的單元測試方法,我想用任意返回值[1-10之間的任何值]替換方法調用memberInstance.xyz(a)。請讓我知道我該怎麼做到這一點?請儘可能提供示例代碼。

回答

5

您應該使用它的接口。

public interface IMemberInstance 
{ 
    int xyz {get;} 
} 

public class MemberInstance : IMemberInstance 
{ 
... // the real class's implementation + code here 
} 

public class MockMemberInstance : IMemberInstance 
{ 
    // the test class can return a test value 
    int xyz(int a) { return 10; } 
} 

然後在您的類進行測試(例如MyClass的)

private IMemberInstance memberInstance; 

public MyClass(IMemberInstance memberInstance) 
{ 
    this.memberInstance = memberInstance; 
} 

int sum(int a, int b) 
{ 
    int x = memberInstance.xyz(a); // memberInstance is an object of another class 
    ..... 
    ..... 
} 

讓這個你可以在IMemberInstance傳遞給類進行測試。這樣,您就可以與測試類(模擬執行)

+0

我已經開發了許多類和這些類的實例越來越在使用其他類。根據您的解決方案,我需要爲所有類開發接口,並且還必須更改實際使用其他類實例的類的代碼(需要引用接口而不是使用實際類的引用)。有沒有其他解決問題的方法? – 2013-03-01 08:40:25

+0

不是真的......這基本上是這樣做的方式。在開發過程中最好牢記測試,因此您不必回頭修改。接口使您可以鬆散地耦合對象的依賴關係的實現,以便輕鬆測試它們。 – Alan 2013-03-01 09:15:51

+0

明白了。將來我會努力發展,牢記這一點。但是如果memberInstance是一個Container類的私有字段,如何在test方法中實例化memberInstance? – 2013-03-01 10:21:45