JavaWebServerを使ってみるテスト
- 2015年06月08日
- CATEGORY- 1. 技術力{技術情報}
こんにちは!
前回はPowerMockitoを使用して仮想レスポンスを返すテストコードでした。
今回はJavaWebServerで同様の処理をしてみます。
今回使用するのはcom.sun.net.httpserverパッケージのHttpServerです。
前回使用したClassに対してHttpRequestを投げます。
仮想サーバなのでlocalhostの8000番ポートで接続することにします。
仮想サーバの起動処理です。
private void startHttpServer() throws IOException { InetSocketAddress address = new InetSocketAddress("localhost", 8000); httpServer = HttpServer.create(address, 0); HttpHandler handler = new HttpHandler() { public void handle(HttpExchange exchange) throws IOException { byte[] response = "test response".getBytes(); exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length); exchange.getResponseBody().write(response); exchange.close(); } }; httpServer.createContext("/test/sample.html", handler); httpServer.start(); }
HttpServerのインスタンスを生成します。
引数としてInetSocketAddressに仮想サーバの設定をしています。
HttpContextで仮想化するPathを設定しています。
J-Unitから実行なのでBeforeアノテーションで初期設定を。
Afterアノテーションで事後処理としてサーバの停止を行っています。
private void stopHttpServer() { httpServer.stop(0); } </java> テストコード部分は前回と一緒です。 <java> public void testCallHttp_Success1() throws IOException { HttpSample httpSample = new HttpSample(); boolean actual = httpSample.callHttp(); assertEquals(true, actual); }
さて実行してみましょう。
このように指定したレスポンスが返却されています。
HttpExchangeでレスポンスコードなどを変更できます。
好みは分かれると思いますが、Mockではなく一応実際のサーバなので
テストに必要な返却値を自在に変更できる利点があると思います。
【関連記事】
SOAPUIの便利な使い方①
SOAPUIの便利な使い方②
SOAPUIの便利な使い方③
SOAPUIの便利な使い方④
SOAPUIの便利な使い方⑤
SOAPUIの便利な使い方⑥
- 2015年06月08日
- CATEGORY- 1. 技術力{技術情報}