Last active
January 20, 2020 14:14
-
-
Save mageddo/ca87beff8b25ff69d8ce4956ebb0f351 to your computer and use it in GitHub Desktop.
InMemoryRestServer for apiclient unit tests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
compile group: 'com.sparkjava', name: 'spark-core', version: '2.9.1' |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import org.junit.rules.ExternalResource; | |
import spark.Spark; | |
import java.io.IOException; | |
import java.io.UncheckedIOException; | |
import java.net.ServerSocket; | |
public class InMemoryRestServer extends ExternalResource { | |
public static final String HOST = "localhost"; | |
private int port; | |
public InMemoryRestServer() { | |
} | |
public static int findFreePort() { | |
try { | |
ServerSocket server = new ServerSocket(0); | |
int port = server.getLocalPort(); | |
server.close(); | |
return port; | |
} catch (IOException e){ | |
throw new UncheckedIOException(e); | |
} | |
} | |
@Override | |
protected void before() throws Throwable { | |
port = findFreePort(); | |
Spark.port(port); | |
Spark.init(); | |
Spark.awaitInitialization(); | |
} | |
public String getURL() { | |
return String.format("http://%s:%s", HOST, port); | |
} | |
public int getPort() { | |
return port; | |
} | |
@Override | |
protected void after() { | |
Spark.stop(); | |
Spark.awaitStop(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment