2017-07-10 5 views
0

HttpURLConnectionを使用するこのクラスのユニットテストケースを書きたいと思います。私は、これまでのアプローチを確定するのに苦労しています。ユニットテストhttpclientを使用するクラス

public class DemoRestClient implements Closeable { 

    private final String instanceId; 
    private final String requestId; 
    private HttpURLConnection conn; 

    public DemoRestClient(String instance, String reqId, String url) { 
     this.instanceId = instance; 
     this.requestId = reqId; 

     try { 
      URL urlRequest = new URL(url); 
      conn = (HttpURLConnection) urlRequest.openConnection(); 
     } catch (IOException iox) { 
      throw new RuntimeException("Failed to connect", iox); 
     } 
    } 

    public InputStream run() { 

     try { 
      conn.setRequestMethod("GET"); 
      conn.setRequestProperty("Accept", "application/json"); 
      conn.setRequestProperty("Accept-Encoding", "gzip"); 

      if (conn.getResponseCode() != 200) { 
       throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode()); 
      } 

      return new GZIPInputStream(conn.getInputStream()); 
     } catch (IOException iox) { 
      throw new RuntimeException("Data fetching failed!", iox); 
     } 
    } 

    @Override 
    public void close() throws IOException { 
     if (conn != null) { 
      conn.disconnect(); 
     } 
    } 
} 

これを行っていれば、少し明るくしてください。ありがとう!

答えて

2

HttpURLConnectionを指定するか、工場にDemoRestClientを委任してHttpURLConnectionを作成する必要があります。

たとえば、次のようにこれらのいずれかの方法で

public DemoRestClient(String instance, String reqId, HttpURLConnection connection) { 
    ... 
    this.conn = connection; 
} 

それとも

public DemoRestClient(String instance, String reqId, ConnectionFactory connectionFactory) { 
    ... 
    this.conn = connectionFactory.create(); 
} 

あなたはDemoRestService内で使用して実際のHttpURLConnectionインスタンスを制御し、その後、あなたはあなたのサポートでそれを模擬するために開始することができます所望の試験挙動。例えば

@Test 
public void someTest() throws IOException { 
    HttpURLConnection connection = Mockito.mock(HttpURLConnection.class); 
    String instance = "..."; 
    String reqId = "..."; 

    DemoRestClient demoRestClient = new DemoRestClient(instance, reqId, connection); 

    // in case you need to mock a response from the conneciton 
    Mockito.when(connection.getInputStream()).thenReturn(...); 

    demoRestClient.run(); 

    // in case you want to verify invocations on the connection 
    Mockito.verify(connection).setRequestMethod("GET"); 
} 
+0

あなたの努力に感謝します! – ProgrammerBoy

+0

あなたは大歓迎です... – glytching

2

あなたはDemoRestClientクラスのうち、HttpURLConnectionオブジェクトの作成を抽出し、コンストラクタで構築され、インスタンスを注入できます。

HttpURLConnectionタイプのモックを作成してユニットテストで使用し、DemoRestClientHttpURLConnectionモックと予想どおりにやりとりすることを確認できます。

+0

あなたの努力に感謝します! – ProgrammerBoy

関連する問題