2009-08-20 83 views
1

我已經準備好了HttpRequest(一個包裝和一個接口)的假對象...因爲我不需要調用構造函數,所以如何在不破壞此方法的接口的情況下傳入假的HttpRequest?如何使用僞對象爲依賴單元測試靜態方法?

public static int ParseQueryInt(string key, int defaultValue) 
{ 
    NameValueCollection nvc; 
    if (HttpContext.Current.Request.QueryString["name"] != null) 
    { 
     //Parse strings. 
    } 
} 

編輯:Akselson的解決方案是最有創造性和這個概念證明的工作,這讓我驚訝的是,雖然我也用飛碟雙向的解決方案,因爲它看起來更可能在所有的情況下工作。

public class Class1 
{ 
    [Test] 
    public void Test() 
    { 
     HttpContext.Current = new HttpContext(
new HttpRequest("test.aspx", "http://test.com/test.aspx", "querystring=value"), 
new HttpResponse(new StringWriter()) 
); 
     Assert.AreEqual(HttpContext.Current.Request.QueryString["querystring"], "value"); 
    } 
} 

回答

4

您可以設置HttpContext.Current到你自己的實例:

HttpContext.Current = new HttpContext(
    new HttpRequest("test.aspx","http://test.com/test.aspx","querystring=value"), 
    new HttpResponse(new StringWriter()) 
); 

,如果你不想讓你擁有它在測試前更改方法可能是有用的。

7

一種選擇是引入另一個過載:

public static int ParseQueryInt(string key, int defaultValue) 
{ 
    return ParseQuery(key, defaultValue, HttpContext.Current.Request); 
} 

public static int ParseQueryInt(string key, int defaultValue, 
           HttpRequest request) 
{ 
    NameValueCollection nvc; 
    if (request.QueryString["name"] != null) 
    { 
     //Parse strings. 
    } 
} 

然後你減少你的「不可驗證」(或者至少是「難以測試」)代碼,以一個簡單的重定向...你可以測試剔除接受請求的版本。

+0

哇,這很快!並且您也在閱讀我的想法:) – 2009-08-20 19:47:06

+6

您可以通過InternalsVisibleTo屬性將內部第二次重載並從測試程序集中使用它。所以你不要將你的API混淆爲單元測試目的。 – 2009-08-20 19:50:00

相關問題