繁体   English   中英

Junit:如何模拟HttpUrlConnection

[英]Junit: How to Mock the HttpUrlConnection

如何在示例代码中模拟HttpURLConnection到getContent()方法,以及如何从模拟URL获取响应

public class WebClient {
   public String getContent(URL url) {
       StringBuffer content = new StringBuffer();
       try {

           HttpURLConnection connection = createHttpURLConnection(url);
           connection.setDoInput(true);
           InputStream is = connection.getInputStream();
           int count;
           while (-1 != (count = is.read())) {
               content.append(new String(Character.toChars(count)));
           }
       } catch (IOException e) {
           return null;
       }
       return content.toString();
   }
   protected HttpURLConnection createHttpURLConnection(URL url) throws IOException{
       return (HttpURLConnection)url.openConnection();

   } 
}

谢谢

您的Webclient设计有点糟糕, Webclient进行测试。 您应该避免隐藏的依赖项(基本上是大多数new操作)。 为了可模仿,这些依赖项应该(优选地)给予被测对象,因为它的构造函数或测试对象应该将它们保存在一个字段中,以便可以注入它们。

或者,您可以扩展您的Webclient

new Webclient() {
  @Override
  HttpURLConnection createHttpURLConnection(URL url) throws IOException{
    return getMockOfURLConnection();
}

其中getMockOfURLConnection从像Mockito这样的模拟框架返回HttpURLConnection的模拟。 然后你教这个模拟返回你想要的东西,并使用verify来检查它是否被正确调用。

您应该重构代码:使用方法URL.openStream()而不是此HttpURLConnectionHttpURLConnection 代码将更简单,更通用,更容易测试。

public class WebClient {
    public String getContent(final URL url) {
        final StringBuffer content = new StringBuffer();
        try {
            final InputStream is = url.openStream();
            int count;
            while (-1 != (count = is.read()))
                content.append(new String(Character.toChars(count)));
        } catch (final IOException e) {
            return null;
        }
        return content.toString();
    }
}

然后,您应该模拟URL 这是最后一堂课,所以你不能用Mockito来嘲笑它。 根据偏好,它仍有几种可能性:

  1. 使用类路径中的假资源进行测试,并使用WebClientTest.class.getResource("fakeResource")来获取URL
  2. 提取一个接口StreamProvider允许从WebClient注入一个URLInputStream
  3. 使用PowerMock模拟 final class URL

您将需要使用存根,看看mockito.org这是一个易于使用的框架。 我们的想法是模仿类的行为并验证您的代码是否处理正面和负面场景。

暂无
暂无

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

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