第一次测试后,junit中的HttpServer因地址使用错误而失败

时间:2012-05-15 19:38:01

标签: java junit com.sun.net.httpserver

我有一个用于JUnit 4.x的Java类。在每个@Test方法中,我创建了一个新的HttpServer,使用了端口9090。第一个调用工作找到,但后续的错误“地址已经在使用:绑定”。

以下是一个例子:

@Test
public void testSendNoDataHasValidResponse() throws Exception {
    InetSocketAddress address = new InetSocketAddress(9090);
    HttpHandler handler = new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = "Hello, world".getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    HttpServer server = HttpServer.create(address, 1);
    server.createContext("/me.html", handler);
    server.start();

    Client client = new Client.Builder(new URL("http://localhost:9090/me.html"), 20, "mykey").build();

    client.sync();
    server.stop(1);
    assertEquals(true, client.isSuccessfullySynchronized());
}

显然,HttpServer仅在每个方法中保存,并在结束前停止。我没有看到什么继续保持任何套接字打开。第一次测试通过,后续测试每次都失败。

有什么想法吗?

使用更正方法编辑:

@Test
public void testSendNoDataHasValidResponse() throws Exception {
    server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1);
    HttpHandler handler = new HttpHandler() {

        @Override
        public void handle(HttpExchange exchange) throws IOException {
            byte[] response = "Hello, world".getBytes();
            exchange.sendResponseHeaders(HttpURLConnection.HTTP_OK, response.length);
            exchange.getResponseBody().write(response);
            exchange.close();
        }
    };
    server.createContext("/me.html", handler);
    server.start();
    InetSocketAddress address = server.getAddress();
    String target = String.format("http://%s:%s/me.html", address.getHostName(), address.getPort());

    Client client = new Client.Builder(new URL(target), 20, "mykey").build();

    client.sync();
    server.stop(0);
    assertEquals(true, client.isSuccessfullySynchronized());
}

3 个答案:

答案 0 :(得分:5)

杰洛的答案就在钱上。

其他解决方法:

答案 1 :(得分:3)

通常需要2分钟的等待时间才能重新绑定到特定的端口号。运行netstat以确认您的服务器连接是否在TIME_WAIT中。如果是这样,您可以在绑定之前使用SO_REUSEADDR选项绕过它。对于java,文档是here

答案 2 :(得分:0)

创建HttpServer时,指定了

  

允许的最大排队传入连接数   听插座

1

server = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 1);

link