简体   繁体   English

如何使用伪造对象的依赖关系对静态方法进行单元测试?

[英]How to unit test a static method using a fake object for the dependency?

I've got my Fake object for HttpRequest ready (a wrapper and an interface)... since I don't need to call a constructor, how do I pass in the fake HttpRequest without breaking the interface of this method? 我已经准备好用于HttpRequest的Fake对象(包装器和接口)...由于不需要调用构造函数,因此如何在不破坏此方法的接口的情况下传递伪造的HttpRequest?

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

EDIT: Akselson's solution is the most creative and this proof of concept worked, much to my surprise, although I also used Skeet's solution as it look more likely to work in all situations. 编辑: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");
    }
}

One option is introduce another overload: 一种选择是引入另一种重载:

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.
   }
}

Then you reduce your "untestable" (or at least "hard to test") code to a simple redirection... you can test the heck out of the version which accepts a request. 然后,将“ unestable”(或至少“难测试”)代码简化为简单的重定向...您可以测试接受请求的版本中的内容。

You can set HttpContext.Current to your own instance: 您可以将HttpContext.Current设置为您自己的实例:

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

It might be useful if you don't want to change the method before you have it under test. 如果您不想在测试之前更改方法,这可能会很有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM