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

标签 java junit com.sun.net.httpserver

我有一个用于 JUnit 4.x 的 Java 类。在每个 @Test 方法中,我创建一个新的 HttpServer,使用端口 9090。第一次调用可以找到,但随后的调用会出现“地址已在使用中:绑定(bind)”的错误。

这是一个例子:

@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());
}

最佳答案

果冻的答案是钱。

其他解决方法:

关于java - 第一次测试后,junit 中的 HttpServer 因地址使用错误而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10607633/

相关文章:

java - org.springframework.batch.core.JobExecutionException : Partition handler returned an unsuccessful step

java - PreparedStatementCallback 覆盖率的 Junit 测试用例

scala - Gradle和Specs2:Specs2-HtmlOutput

java - com.sun.net.httpserver.HttpServer 最大连接数?

JavaHTTPServer 在 (html) 按钮上单击获取 (html) 文本框的内容

java - 如何将 'JOptionPane.showConfirmDialog' 弹出窗口的默认焦点从 'Ok' 按钮更改为 'textfield' ?

java - 无法在 Eclipse 中运行/调试 Java 应用程序(JavaTimeZone 问题)

java - 如何使用 JUnit 测试 Java 中的任何输出

java - JRE HttpServer 是否违反了 HTTP 的 'expect-continue' 语义?

java - Xtend 构建失败,java 包含无效字符