Skip to content

Instantly share code, notes, and snippets.

@sergekukharev
Created December 31, 2021 16:19
Show Gist options
  • Save sergekukharev/c4f3efa77fb602ab8b30402084c2f311 to your computer and use it in GitHub Desktop.
Save sergekukharev/c4f3efa77fb602ab8b30402084c2f311 to your computer and use it in GitHub Desktop.
Spark Java server starter

Spark Java server starter

Good to use with unit/integration tests of Spark Java app.

Warning!

Spark Java is pretty much dead

Configuration

App is your main Spark class that registeres all the routes in it's main method.

Usage

Typical integration test case would look like this:

final class AppTest {
    final HttpClient client = HttpClient.newHttpClient();

    URI baseUrl;

    @BeforeEach
    void setUp() {
        SparkServerStarter.start();
        baseUrl = URI.create("http://localhost:" + Spark.port());
    }

    @Test
    void testRunning() throws IOException, InterruptedException {
        var request = HttpRequest.newBuilder()
                .uri(baseUrl.resolve("/hello"))
                .build();

        assertEquals(200, client.send(request, HttpResponse.BodyHandlers.ofString()).statusCode());
    }
}
import spark.Spark;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
public class SparkServerStarter extends App {
public static void start() {
try {
if (isRunning()) {
return;
}
} catch (IllegalStateException e) {
// Intentionally doing nothing
}
var args = new String[0];
App.main(args);
Spark.awaitInitialization();
}
private static boolean isRunning() {
var client = HttpClient.newHttpClient();
var request = HttpRequest.newBuilder()
.uri(URI.create("http://localhost:" + Spark.port() + "/_ready"))
.build();
try {
return client.send(request, HttpResponse.BodyHandlers.ofString()).statusCode() == 200;
} catch (IOException | InterruptedException e) {
e.printStackTrace();
throw new RuntimeException("Failed to ping the server");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment