11package com .baeldung .socket ;
22
33import org .junit .BeforeClass ;
4+ import org .junit .Ignore ;
45import org .junit .Test ;
56
7+ import java .io .IOException ;
8+ import java .net .ServerSocket ;
69import java .util .concurrent .Executors ;
710
811import static org .junit .Assert .assertEquals ;
912
1013public class SocketEchoMultiIntegrationTest {
1114
12- private static final Integer PORT = 5555 ;
15+ private static int port ;
1316
1417 @ BeforeClass
15- public static void start () throws InterruptedException {
16- Executors .newSingleThreadExecutor ().submit (() -> new EchoMultiServer ().start (PORT ));
18+ public static void start () throws InterruptedException , IOException {
19+
20+ // Take an available port
21+ ServerSocket s = new ServerSocket (0 );
22+ port = s .getLocalPort ();
23+ s .close ();
24+
25+ Executors .newSingleThreadExecutor ().submit (() -> new EchoMultiServer ().start (port ));
1726 Thread .sleep (500 );
1827 }
1928
2029 @ Test
2130 public void givenClient1_whenServerResponds_thenCorrect () {
2231 EchoClient client = new EchoClient ();
23- client .startConnection ("127.0.0.1" , PORT );
32+ client .startConnection ("127.0.0.1" , port );
2433 String msg1 = client .sendMessage ("hello" );
2534 String msg2 = client .sendMessage ("world" );
2635 String terminate = client .sendMessage ("." );
@@ -34,7 +43,7 @@ public void givenClient1_whenServerResponds_thenCorrect() {
3443 @ Test
3544 public void givenClient2_whenServerResponds_thenCorrect () {
3645 EchoClient client = new EchoClient ();
37- client .startConnection ("127.0.0.1" , PORT );
46+ client .startConnection ("127.0.0.1" , port );
3847 String msg1 = client .sendMessage ("hello" );
3948 String msg2 = client .sendMessage ("world" );
4049 String terminate = client .sendMessage ("." );
@@ -47,7 +56,7 @@ public void givenClient2_whenServerResponds_thenCorrect() {
4756 @ Test
4857 public void givenClient3_whenServerResponds_thenCorrect () {
4958 EchoClient client = new EchoClient ();
50- client .startConnection ("127.0.0.1" , PORT );
59+ client .startConnection ("127.0.0.1" , port );
5160 String msg1 = client .sendMessage ("hello" );
5261 String msg2 = client .sendMessage ("world" );
5362 String terminate = client .sendMessage ("." );
0 commit comments