2

サンプルコードの getContent() メソッドに HttpURLConnection をモックする方法 , またモック 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();

   } 
}

ありがとう

4

3 に答える 3

2

コードをリファクタリングする必要があります。このキャストの代わりにメソッドURL.openStream()HttpURLConnectionを使用してください。コードはより単純で、より一般的なものになり、テストが容易になります。

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を取得できるようにします。InputStreamURLWebClient
  3. をモックするためにPowerMockを使用しfinal class URLます。
于 2012-09-06T07:58:54.600 に答える