簡體   English   中英

單元測試java中的套接字

[英]unit testing sockets in java

我有一個類是一個套接字客戶端,我試圖對其方法進行單元測試。 測試要求我在每次測試之前啟動套接字服務器,所以我使用:

@Before
public void setUp() {
    if (myServerSocket == null) {
    Thread myThread = new Thread() {
        public void run() {
            DataInputStream dis = null;
            DataOutputStream dos = null;
            try {
                ServerSocket myServer = new ServerSocket(port);
                myServerSocket = myServer.accept();
                dis = new DataInputStream(myServerSocket.getInputStream());
                dos = new DataOutputStream(myServerSocket.getOutputStream());
                byte[] bytes = new byte[10];
                dis.read(bytes);
                boolean breakLoop = false;
                do {
                    if (new String(bytes).length() != 0) {
                        dos.writeBytes(serverMessage + "\n");
                        dos.flush();
                        breakLoop = true;
                        dos.writeBytes("</BroadsoftDocument>" + "\n");
                        dos.flush();
                    }
                } while (!breakLoop);
            } 
            catch (IOException e) {
                e.printStackTrace();
            }
        }
    };
    myThread.start();
    }
} 

在每次測試后,我嘗試關閉服務器套接字,以便我可以重新打開服務器套接字以進行下一個測試:

@After
public void tearDown() throws IOException, BroadsoftSocketException {
    System.out.println("@After");
    if (myServerSocket != null) {
        myServerSocket.close();
        myServerSocket = null;
            try {
                Thread.sleep(5000);
            } 
            catch (InterruptedException e) {
                // do nothing.
            }
    }
}

但是,在第二次測試開始的每次測試之前,我得到“java.net.BindException:Address in in use:JVM_Bind”。 我意識到我試圖為每個測試使用相同的端口,但是不應該關閉套接字釋放端口?

當您嘗試重新連接時,您的套接字可能仍處於TIME_WAIT狀態。 我建議模擬這樣的外部依賴項,但如果你確實發現自己想要繼續使用真正的套接字,那么嘗試設置重新綁定選項。 在您的安裝功能中,而不是ServerSocket myServer = new ServerSocket(port); 做:

final ServerSocket myServer = new ServerSocket();
myServer.setReuseAddress(true);
myServer.bind(new java.net.InetSocketAddress(port));
  1. 您已經在“setUp”中關閉了您的serversocket,您真的應該在finally塊中執行它。
  2. 端口可能不會立即釋放。 您可以通過將ServerSocket的reuseAdress設置為true來避免這種true 請參見setReuseAddress

而我第二個SimonC:也許你最好先避開套接字。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM