JUnit测试挂起在clientSocket.accept()?

时间:2015-12-05 11:00:34

标签: java sockets testing junit server

我需要使用JUnit测试一些客户端/服务器应用程序,并且我在测试客户端与服务器的连接时遇到问题。似乎测试挂起在" Socket clientSocket = serverSocket.accept()"在服务器类中排队,它不允许我连接新客户端。

这是JUnit类:

 @Test
        public void testNetServerComm_1() throws Exception {
            server = new NetServerComm();
            assertNotNull(server);
        }

        @Test
        public void testAddMessageToQueue_1() throws Exception {
            NetServerComm fixture = new NetServerComm();
            NetServerSideMessage msg = new NetServerSideMessage(birdsong.comm.ServerSideMessage.Type.BIRDSONG_MESSAGE, "",
                    "");
            fixture.addMessageToQueue(msg);
            assertEquals(1, fixture.getMsgQueueSize());
        }

    @Test
        public void testClientIsConnected_1() throws Exception {
            NetServerComm fixture = new NetServerComm();
            fixture.start();

            //test doesn't go further that this..

            String nickname = "john";
            new NetClientComm().connect("127.0.0.1", nickname);
            boolean result = fixture.isClientConnected(nickname);
            assertTrue(result);
        }

客户类:

//connects to the server
@Override
    public void connect(String host, String nickname) {
        try {
            clientNickname = nickname;
            System.out.println("Address= " + host + " and NickName = " + nickname);
            socket = new Socket(host, NetServerComm.PORTO); //8080
            System.out.println("Socket = " + socket);
            serverMsg = new NetServerSideMessage(ServerSideMessage.Type.CLIENT_CONNECTED, null, clientNickname);
            out = new ObjectOutputStream(socket.getOutputStream());
            out.writeObject(serverMsg);
            isConnected = true;
            messageHandler = new Thread(new MessageHandler(socket));
            messageHandler.start();
        } catch (IOException e) {
            System.out.println("Failed connecting to the server.");
            e.printStackTrace();
        }
    }

服务器类:

//starts the server
@Override
    public void start() {
        try {
            serverSocket = new ServerSocket(PORTO); //8080
            System.out.println("Servidor is online: " + serverSocket);
            try {
                while (true) {
                    Socket clientSocket = serverSocket.accept();

                     //test hangs at the method above^^^

                    checkNewClient(clientSocket);
                    if (nameCheck == true)
                        new Thread(new ClientHandler(clientSocket)).start();
                }
            } finally {
                System.out.println("Closing the server..");
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

1 个答案:

答案 0 :(得分:1)

看起来你的start()方法是由与测试相同的Thread执行的,因此它会阻塞(在accept()部分)。您是否可以尝试通过新线程执行此方法? - 伯杰

这似乎完成了工作:) - JDev