2012-05-17 44 views
11

メソッド自体を変更せずに次のメソッドをテストする必要があります。 このメソッドはPOSTメソッドをサーバーに作成します。しかし、私はサーバーから独立したテストケースを作る必要があります。Java JunitテストHTTP POSTリクエスト

同様の方法をローカルファイルにリダイレクトする前にテストしました。 しかし、私はファイルとしてプロトコルを与えていました。ホスト名はlocalhost、ポートは-1です。

私の問題は、このメソッドは投稿を行い、HttpURLConnectionとwr = new DataOutputStream(conn.getOutputStream())にキャストすることです。 httpを介してローカルtxtファイルで作業しません。

//コンストラクタ

public HTTPConnector(String usr, String pwd, String protocol, 
      String hostname, int port) { 
     this.usr = usr; 
     this.pwd = pwd; 
     this.protocol = protocol; 
     this.hostname = hostname; 
     this.port = port; 

     // connect(); 
    } 

は//私は

public String doPost(String reference, String data) throws IOException { 
     URL url = null; 
     HttpURLConnection conn = null; 
     BufferedReader rd = null; 
     DataOutputStream wr = null; 
     InputStream is = null; 
     String line = null; 
     StringBuffer response = null; 

     url = new URL(protocol, hostname, port, reference); 
     conn = (HttpURLConnection) url.openConnection(); 

     conn.setRequestMethod("POST"); 

     conn.setRequestProperty("Authorization", "Basic dGVzdDphc2Rm"); 
     conn.setRequestProperty("Content-Type", "application/xml"); 

     conn.setUseCaches(false); 
     conn.setDoInput(true); 
     conn.setDoOutput(true); 

     // Send response 
     wr = new DataOutputStream(conn.getOutputStream()); 
     wr.writeBytes(data); 
     wr.flush(); 
     wr.close(); 

     // Get response 
     is = conn.getInputStream(); 
     rd = new BufferedReader(new InputStreamReader(is)); 
     response = new StringBuffer(); 
     while ((line = rd.readLine()) != null) { 
      response.append(line); 
      response.append('\r'); 
     } 
     rd.close(); 
     return response.toString(); 
    } 

//メソッドをテストする必要があります方法は、私が

public String doGet(String reference) throws IOException { 
     connect(); 
     URL url = new URL(protocol, hostname, port, reference); 
     InputStream content = (InputStream) url.getContent(); 

     BufferedReader xml = new BufferedReader(new InputStreamReader(content)); 
     return xml.readLine(); 
    } 
+0

あなたはモックオブジェクトを使って見ましたか? – buymypies

+0

私はそれがどのようにリダイレクトするのが難しいか分かりません。私はそれをローカルファイルやクラスにリダイレクトする方法を見つけることができる場合、私は回避策を作ることができますが、私が見ることができる唯一の方法はローカルサーバー/スレッドを作ることです。しかし、それは私がサーバーにデータを取得するために私のテストを指示しなければならないことを意味し、サーバーは自己が要求するためにハンドリングする必要があり、効率的にはるかに多くの作業が必要です。 – Gabain1993

答えて

6

が、ここでサンプルテストのテストでした。私が作ったアサーションはデモの目的であり、あなたのニーズに適応する必要があることに注意してください。

@RunWith(PowerMockRunner.class) 
@PrepareForTest({ toTest.class, URL.class, HttpURLConnection.class }) 
public class soTest { 
    /** 
    * test response. 
    */ 
    private static final String TEST_RESPONSE = "test\nresponse"; 

    /** 
    * test data. 
    */ 
    private static final String DATA = RandomStringUtils.randomAscii(125); 

    /** 
    * test port. 
    */ 
    private static final int PORT = 8080; 

    /** 
    * test hosts. 
    */ 
    private static final String HOSTNAME = "hostname"; 

    /** 
    * test protocol. 
    */ 
    private static final String PROTOCOL = "http"; 

    /** 
    * test reference. 
    */ 
    private static final String REFERENCE = "REFERENCE"; 

    /** 
    * URL mock. 
    */ 
    private URL url; 

    /** 
    * HttpURLConnection mock. 
    */ 
    private HttpURLConnection connection; 

    /** 
    * Our output. 
    */ 
    private ByteArrayOutputStream output; 

    /** 
    * Our input. 
    */ 
    private ByteArrayInputStream input; 

    /** 
    * Instance under tests. 
    */ 
    private toTest instance; 

    @Before 
    public void setUp() throws Exception 
    { 
     this.url = PowerMockito.mock(URL.class); 
     this.connection = PowerMockito.mock(HttpURLConnection.class); 

     this.output = new ByteArrayOutputStream(); 
     this.input = new ByteArrayInputStream(TEST_RESPONSE.getBytes()); 
     this.instance = new toTest(PROTOCOL, HOSTNAME, PORT); 

     PowerMockito.whenNew(URL.class).withArguments(PROTOCOL, HOSTNAME, PORT, REFERENCE).thenReturn(this.url); 
    } 

    @Test 
    public void testDoPost() throws Exception 
    { 
     PowerMockito.doReturn(this.connection).when(this.url).openConnection(); 
     PowerMockito.doReturn(this.output).when(this.connection).getOutputStream(); 
     PowerMockito.doReturn(this.input).when(this.connection).getInputStream(); 

     final String response = this.instance.doPost(REFERENCE, DATA); 

     PowerMockito.verifyNew(URL.class); 
     new URL(PROTOCOL, HOSTNAME, PORT, REFERENCE); 

     // Mockito.verify(this.url).openConnection(); // cannot be verified (mockito limitation) 
     Mockito.verify(this.connection).getOutputStream(); 
     Mockito.verify(this.connection).setRequestMethod("POST"); 
     Mockito.verify(this.connection).setRequestProperty("Authorization", "Basic dGVzdDphc2Rm"); 
     Mockito.verify(this.connection).setRequestProperty("Content-Type", "application/xml"); 
     Mockito.verify(this.connection).setUseCaches(false); 
     Mockito.verify(this.connection).setDoInput(true); 
     Mockito.verify(this.connection).setDoOutput(true); 
     Mockito.verify(this.connection).getInputStream(); 

     assertArrayEquals(DATA.getBytes(), this.output.toByteArray()); 
     assertEquals(TEST_RESPONSE.replaceAll("\n", "\r") + "\r", response); 
    } 
} 


@Data 
public class toTest { 
    private final String protocol, hostname; 

    private final int port; 

    public String doPost(String reference, String data) throws IOException 
    { 
     // your method, not modified 
    } 
} 

依存性:

  • コモンズ - ラング2.5
  • powermock-API-mockito 1.4.11
  • powermockモジュール-junit4 1.4.11
  • のJUnit 4.10
  • ロンボクテストクラスの0.11.0
+1

それは良い解決策のようですが、私はエラーが発生し、解決方法を知らないかもしれませんが、いくつかの光を放つことができます:タイプorg.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunnerを解決することはできません。間接的には \tが必要な.classファイルから参照されています – Gabain1993

+0

このクラスは 'powermock-module-junit4'によって提供されています。クラスパスを確認する必要があります –

5

テスト中のメソッドをリファクタリングする機会がない場合は、それが使用するHttpUrlConnectionを偽装するという新しいアプローチがあります。最初は、HttpUrlConnectionがパラメータとして渡されないため、これは難しいようです。ただし、これを制御するには、url.openConnectionから返される接続を制御します。

これはコンストラクタに渡すプロトコルのためにjava.net.URLで登録されたプロトコルハンドラによって管理されます。そのトリックは、新しいプロトコルハンドラを登録することです(詳細は、Java - Registering custom URL protocol handlersを参照してください)。

新しいプロトコルハンドラは、あなたのテストで使用できる模擬HttpUrlConnectionを返します。

関連する問題