package com.ahmedmusallam.extension; import com.sun.net.httpserver.HttpHandler; import com.sun.net.httpserver.HttpServer; import java.net.InetSocketAddress; import java.net.URI; import java.net.URISyntaxException; import org.apache.http.client.utils.URIBuilder; import org.junit.jupiter.api.extension.AfterAllCallback; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; /* * Note: I chose to implement `BeforeAllCallback` and AfterAllCallback * but not `AfterEachCallback` and `BeforeEachCallback` for performance reasons. * I wanted to only run one server per test class and I can register handlers * on a per-test-method basis. You could implement the `BeforeEachCallback` and `AfterEachCallback` * interfaces if you really need that behavior. */ public class HttpServerExtension implements BeforeAllCallback, AfterAllCallback { public static final int PORT = 6991; public static final String HOST = "localhost"; public static final String SCHEME = "http"; private com.sun.net.httpserver.HttpServer server; @Override public void afterAll(ExtensionContext extensionContext) throws Exception { if (server != null) { server.stop(0); // doesn't wait all current exchange handlers complete } } @Override public void beforeAll(ExtensionContext extensionContext) throws Exception { server = HttpServer.create(new InetSocketAddress(PORT), 0); server.setExecutor(null); // creates a default executor server.start(); } public static URI getUriFor(String path) throws URISyntaxException{ return new URIBuilder() .setScheme(SCHEME) .setHost(HOST) .setPort(PORT) .setPath(path) .build(); } public void registerHandler(String uriToHandle, HttpHandler httpHandler) { server.createContext(uriToHandle, httpHandler); } }