[英]Is it possible to unit test this method?
我嘗試使用以下方法來編寫單元測試:
using StaticClass; // writen by some one else, have a dll
namespace Test
{
Class TestClass
{
public void DoSomething(string param1)
{
List<string> = StaticClass.GetList(param1)
// sort the list and do other studd here
}
}
}
當我不確定如何為DoSomething方法編寫測試時,這取決於另一個類中的靜態方法。 該方法的輸出取決於諸如該計算機上的數據庫,環境以及其他一些其他因素。 因此,如果兩台計算機上的數據庫不同,則相同的方法將得出不同的結果。 我所知道的是GetList返回一些值,並且該方法的創建者可能已對該方法進行了單元測試,也可能未對該方法進行過測試。
如何測試這種方法? 每當調用StaticClass.Getlist方法時,是否都可以說類似的話,返回我在程序中創建的自定義List<String>
? 我正在用C#編寫測試。
謝謝,
具有副作用的方法的靜態類型很麻煩。
您有兩種選擇:
這是有時不贊成以這種方式使用靜態的原因之一-盡管很方便,但它們很難測試。
一種方法是將該類的工作抽象為其他內容。
例如,您可以聲明
public interface ISomeonesDllService
{
IList<string> GetList(string param1);
}
現在創建一個使用StaticClass
的實現:
public class SomeonesDllService : ISomeonesDllService
{
public IList<string> GetList(string param1)
{
return StaticClass.GetList(param1);
}
}
為了使TestClass
可測試,您可以在類構造函數中注入對此外部服務的依賴關系:
public class TestClass
{
ISomeonesDllService dllService;
public TestClass(ISomeonesDllService dllService)
{
this.dllService = dllService;
}
public void DoSomething(string param1)
{
IList<string> strings = dllService.GetList(param1);
// do work
}
}
現在,您可以非常輕松地測試DoSomething()
方法,因為在測試夾具中,您可以使用ISomeonesDllService
的不同實現實例化TestClass
。 您可以手動滾動僅返回靜態字符串列表的存根,也可以使用諸如Rhino.Mocks之類的模擬框架為您進行設置(我建議)。
這樣,您可以將DoSomething()
與外部依賴項的工作隔離開。
您將需要使用Mock對象來測試這種事情。 看到這篇很棒的文章: http : //gamesfromwithin.com/mock-objects-friends-or-foes
基本上,您將創建一個對象,該對象可以模擬與其交互的對象,然后驗證您的期望。
如果我看到此權利,則此方法將無法編譯。 但是,如果您想在靜態類中測試該方法,則可以單獨進行測試。
您的類中的方法不返回任何內容。 如果在系統中只有輸入,則無需實現它。
您可以為靜態類創建一個非靜態包裝器,而改用包裝器。
就像是
Class StaticClassWrapper {
public List<string> GetList(string param1) {
return StaticClass.GetList(param1);
}
}
然后在您的TestClass中使用包裝器而不是靜態類
使StaticClass成為您可以使用Moq,Rhino等進行模擬的依賴項。然后,您可以隨意模擬StaticClass以返回已知的List<string>
或只是驗證它是否通過模擬被調用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.