LoginSignup
9
9

More than 5 years have passed since last update.

JREに同梱のcom.sun.net.httpserverを使ってHTTPのテストをする方法

Last updated at Posted at 2012-10-08

もちろんJettyでもいいんだけど、
JREしか使いたくない場合は以下のようにすると、
テストコードの中でHttpServerを作ってレスポンスの受け側のテストが出来ます。

MyTests.java
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import static org.junit.Assert.*;

import org.junit.Test;
import com.sun.net.httpserver.*;

public class MyTests {
        @Test
        public void httpServer_API_test() throws Exception {
              HttpServer httpServer = HttpServer. create( new InetSocketAddress("localhost" ,8080),8080);
              ExecutorService httpThreadPool = Executors. newFixedThreadPool(1);
              httpServer.setExecutor(httpThreadPool);
              httpServer.createContext( "/" ,new HttpHandler(){
                      @Override
                      public void handle(HttpExchange exc) throws IOException {
                           final String response = "Hello HTTP Server" ;
                           exc.sendResponseHeaders(200, response.length());
                           OutputStream os = exc.getResponseBody();
                           os.write(response.getBytes());
                           os.close();
                     }
              });
              httpServer.start();
               // TODO:なんやらかんやらテスト
              httpServer.stop(1);
              httpThreadPool.shutdownNow();
       }
}

上記は、ポートが既に使われているとか例外処理とか知ったこっちゃないコードなので、
コピペには注意してください。

9
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9