Skip to content

Instantly share code, notes, and snippets.

@mageddo
Last active January 20, 2020 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mageddo/ca87beff8b25ff69d8ce4956ebb0f351 to your computer and use it in GitHub Desktop.
Save mageddo/ca87beff8b25ff69d8ce4956ebb0f351 to your computer and use it in GitHub Desktop.
InMemoryRestServer for apiclient unit tests
compile group: 'com.sparkjava', name: 'spark-core', version: '2.9.1'
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