[英]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.