C# 如何使用伪对象对依赖项进行静态方法单元测试?
我已经为HttpRequest准备好了假对象(包装器和接口)。。。由于我不需要调用构造函数,如何在不破坏该方法的接口的情况下传入伪HttpRequestC# 如何使用伪对象对依赖项进行静态方法单元测试?,c#,unit-testing,C#,Unit Testing,我已经为HttpRequest准备好了假对象(包装器和接口)。。。由于我不需要调用构造函数,如何在不破坏该方法的接口的情况下传入伪HttpRequest public static int ParseQueryInt(string key, int defaultValue) { NameValueCollection nvc; if (HttpContext.Current.Request.QueryString["name"] != null) { //Pars
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.
}
}
然后将“不稳定”(或至少“难以测试”)代码简化为简单的重定向。。。您可以测试接受请求的版本。一个选项是引入另一个重载:
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.
}
}
然后将“不稳定”(或至少“难以测试”)代码简化为简单的重定向。。。您可以测试接受请求的版本。您可以将HttpContext.Current设置为您自己的实例:
HttpContext.Current = new HttpContext(
new HttpRequest("test.aspx","http://test.com/test.aspx","querystring=value"),
new HttpResponse(new StringWriter())
);
如果您不想在测试方法之前更改该方法,那么它可能会很有用。您可以将HttpContext.Current设置为您自己的实例:
HttpContext.Current = new HttpContext(
new HttpRequest("test.aspx","http://test.com/test.aspx","querystring=value"),
new HttpResponse(new StringWriter())
);
如果您不想在测试方法之前更改它,它可能会很有用。您可以将第二个重载设置为内部重载,并通过InternalsVisibleTo属性从测试程序集中使用它。因此,您不必为了单元测试而使API混乱。您可以将第二个重载设置为内部重载,并通过InternalsVisibleTo属性从测试程序集中使用它。因此,您不会为了单元测试目的而使API变得杂乱无章。