✅ Prevent test from starting if local server is not yet up
authorDavid ‘Bombe’ Roden <bombe@freenetproject.org>
Tue, 3 Sep 2024 09:19:41 +0000 (11:19 +0200)
committerDavid ‘Bombe’ Roden <bombe@freenetproject.org>
Tue, 3 Sep 2024 13:06:44 +0000 (15:06 +0200)
src/test/java/net/pterodactylus/fcp/test/LocalServer.java

index 9ab5558..62ee38b 100644 (file)
@@ -22,6 +22,7 @@ import org.junit.rules.ExternalResource;
 import java.io.IOException;
 import java.net.ServerSocket;
 import java.net.Socket;
+import java.util.concurrent.CountDownLatch;
 
 /**
  * Opens a local {@link ServerSocket} for use in a unit test.
@@ -60,6 +61,11 @@ public class LocalServer extends ExternalResource {
        }
 
        public Socket getSocket() {
+               try {
+                       connectedLatch.await();
+               } catch (InterruptedException e) {
+                       throw new RuntimeException(e);
+               }
                return socket;
        }
 
@@ -68,6 +74,7 @@ public class LocalServer extends ExternalResource {
                new Thread(() -> {
                        try {
                                socket = serverSocket.accept();
+                               connectedLatch.countDown();
                        } catch (IOException e) {
                                if (!finished) {
                                        throw new RuntimeException(e);
@@ -95,6 +102,7 @@ public class LocalServer extends ExternalResource {
        }
 
        private final ServerSocket serverSocket;
+       private final CountDownLatch connectedLatch = new CountDownLatch(1);
        private volatile boolean finished = false;
        private volatile Socket socket;