[英]How to unit test a static method using a fake object for the dependency?
我已經准備好用於HttpRequest的Fake對象(包裝器和接口)...由於不需要調用構造函數,因此如何在不破壞此方法的接口的情況下傳遞偽造的HttpRequest?
public static int ParseQueryInt(string key, int defaultValue)
{
NameValueCollection nvc;
if (HttpContext.Current.Request.QueryString["name"] != null)
{
//Parse strings.
}
}
編輯:Akselson的解決方案是最具創意的,這種概念證明行之有效,令我驚訝的是,盡管我也使用了Skeet的解決方案,因為它看起來很可能在所有情況下都可以使用。
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");
}
}
一種選擇是引入另一種重載:
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.
}
}
然后,將“ unestable”(或至少“難測試”)代碼簡化為簡單的重定向...您可以測試接受請求的版本中的內容。
您可以將HttpContext.Current設置為您自己的實例:
HttpContext.Current = new HttpContext(
new HttpRequest("test.aspx","http://test.com/test.aspx","querystring=value"),
new HttpResponse(new StringWriter())
);
如果您不想在測試之前更改方法,這可能會很有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.