首页 > 解决方案 > 在单个 jUnit 测试中运行多个 Jetty 服务器

问题描述

我正在尝试在 jUnit 测试中启动多个码头服务器(每个在不同的端口上),并为每个码头服务器测试相同的休息端点。

我能够成功启动它们,但是每当我查询任何服务器上的端点时,无论我将请求发送到哪个端口,请求总是由单个码头服务器接收。

我已经确认码头服务器都在不同的端口上启动,并且在每个端口上都有一个服务监听。只是请求总是在同一个端口上接收,而不管它实际发送到哪个端口。

是否不可能在不同端口上启动多个码头服务器服务于同一路径?有没有人能够做到这一点?

代码 :

    // Starting the jettyServer
    jettyServer = new Server();
    handlerCollection = new HandlerCollection(true);
    ServerConnector serverConnector = new ServerConnector(jettyServer);

    // The port is passed in to this class. Verified that this is being done correctly.
    serverConnector.setPort(this.port);
    jettyServer.setConnectors(new ServerConnector[] { serverConnector });
    jettyServer.setHandler(handlerCollection);
    jettyServer.start();

    // Config has been configured correctly for the application, verified that
    ServletContextHandler context = new ServletContextHandler();
    context.setContextPath(conf.getString("pathForRestContext"));
    org.glassfish.jersey.server.ResourceConfig config = new ResourceConfig();
    config.packages(conf.getString("packageForRest"));
    ServletHolder servletHolder = new ServletHolder(new ServletContainer(config));
    context.addServlet(servletHolder, "/*");

    // Append our handler to any existing handlers
    handlerCollection.addHandler(newHandler);
    try {
        newHandler.start();
    } catch (Exception e) {
        LOG.error("Error starting new handler: ", e);
        throw e;
    }

    // Sending the request
    URI uri = new URIBuilder()
        .setScheme(httpProtocol)
        .setHost(server.getHostName())
        .setPort(portForJetty)
        .setPath(restEndpoint)
        .build();

    // Using the same httpclient for all of the requests, however using individual clients does not solve the problem.
    Response response = httpClient.target(uri).request(MediaType.APPLICATION_JSON).get();

    // responseType is a custom class which is the expected data type for the incoming data.
    response.readEntity(responseType)

标签: javarestmavenjunitjetty

解决方案


推荐阅读