如何用嵌入式码头进行单元测试websocket?

时间:2015-10-10 07:35:20

标签: websocket jetty embedded-jetty

我想使用嵌入式Jetty为我的websocket serverendpoint代码编写Junit UT案例。

我尝试了以下链接中解释的内容: JUnit test with javax.websocket on embedded Jetty throws RejectedExecutionException: NonBlockingThread

我想测试我对webocket的onMessage回调。 如果我不使用server.join()方法,则连接一打开就会关闭。 如果我使用server.join()方法,加入后没有任何反应。

以下是我的代码。

服务器启动代码::

public class EmbeddedJettyServer {

private final int port;
    private Server server;

    public EmbeddedJettyServer(int port) {
        this.port = port;
    }

    public void start() throws Exception {
        server = new Server();
        ServerConnector connector = new ServerConnector(server);
        connector.setPort(8080);
        server.addConnector(connector);

        // Setup the basic application "context" for this application at "/"
        // This is also known as the handler tree (in jetty speak)
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");
        server.setHandler(context);

        try {
            // Initialize javax.websocket layer
            ServerContainer wscontainer = WebSocketServerContainerInitializer.configureContext(context);

            // Add WebSocket endpoint to javax.websocket layer
            wscontainer.addEndpoint(WebSocketServer.class);
            System.out.println("Begin start");
            server.start();
            server.dump(System.err);
            server.join();


        } catch (Throwable t) {
            t.printStackTrace(System.err);
        }
    }

    public void stop() throws Exception {
        server.stop();
        LOGGER.info("Jetty server stopped");
    }

    public URI getWebsocketUri(Class<WebSocketServer> class1) {         
        return  server.getURI();
    }

}

客户代码:

 @ClientEndpoint()
public class WebSocketClientJetty {

WebSocketContainer container;

public  Session connect(URI uri) throws Exception {
    WebSocketContainer container = ContainerProvider.getWebSocketContainer();

    try {
        // Attempt Connect
          Session session = container.connectToServer(WebSocketClientJetty.class,uri);
       // return container.connectToServer(WebSocketClientJetty.class, uri);
          session.getBasicRemote().sendText("Hello");
            // Close session
          // session.close();

            return session;
    } finally {


    }
}

public  void stop() throws Exception{
    if (container instanceof LifeCycle) {
        ((LifeCycle) container).stop();
    }
}

@OnOpen
public void onWebSocketConnect(Session sess)
{
    System.out.println("Socket Connected: " + sess);
}

@OnMessage
public void onWebSocketText(String message)
{
    System.out.println("Received TEXT message: " + message);
}

@OnClose
public void onWebSocketClose(CloseReason reason)
{
    System.out.println("Socket Closed: " + reason);
}

@OnError
public void onWebSocketError(Throwable cause)
{
    cause.printStackTrace(System.err);
}

}

Serverendpoint代码:

@ServerEndpoint(value = "/echo",
encoders={JsonEncoder.class}) 
public class WebSocketServer {

private static final Logger LOGGER = 



@OnOpen
public void onOpen(Session session){
    System.out.println("onopen");
    some code....
}



@OnMessage
public void onMessage(String message, Session session) throws IOException{
    System.out.println("onmessage");
    ....
}


@OnClose
public void onClose(Session session){
    System.out.println("onClose");
    ...
}

}

大概:

public class WebSocketJettyTest {

private static EmbeddedJettyServer server;

@ClassRule
public static final ExternalResource integrationServer = new ExternalResource() {
    @Override
    protected void before() throws Throwable {
        System.out.println("Starting...");
        server = new EmbeddedJettyServer(8080);
        server.start();
        System.out.println("Started");
    }
};


@Before
public void setUp() throws Exception {

}

@After
public void shutdown() throws Exception {
    server.stop();
}

@Test
public void testSocket() throws Exception {
    /*URI uri = server.getWebsocketUri(WebSocketServer.class);*/
    URI uri = URI.create("ws://localhost:8080/echo");
    WebSocketClientJetty client = new WebSocketClientJetty();
    Session session = client.connect(uri);
    session.getBasicRemote().sendText("hello");
    Thread.sleep(6000);
    client.stop();
}

}

1 个答案:

答案 0 :(得分:1)

将通话转至

server.join();

这只会让当前线程等到服务器线程停止。 这让你很难。