Skip to content

Instantly share code, notes, and snippets.

@bondolo
Created February 25, 2021 23:23
Show Gist options
  • Save bondolo/dad4ecc936117fc30b460d65fffe36fd to your computer and use it in GitHub Desktop.
Save bondolo/dad4ecc936117fc30b460d65fffe36fd to your computer and use it in GitHub Desktop.
Using JDK HttpServer in a JUnit test
/*
* Copyright © 2017 Mike Duigou.
* Public Domain. No Rights Reserved.
*/
public class URLTest {
private static final Logger LOGGER = Logger.getLogger(URLTest.class.getSimpleName());
private static final int TEST_FILE_SIZE = 1 << 20;
private static final String SOURCE_FILE_NAME = "test.file";
private static final String SOURCE_FILE_PATH = "/" + SOURCE_FILE_NAME;
private static final Random RANDOM = DEBUG ? new Random(0) : new Random();
private static final byte[] TEST_DATA = new byte[TEST_FILE_SIZE];
static {
RANDOM.nextBytes(TEST_DATA);
}
private static URL source;
private static HttpServer server;
@BeforeClass
public static void setUp() throws Exception {
InetSocketAddress address = new InetSocketAddress(InetAddress.getLoopbackAddress(), 0);
server = HttpServer.create(address, 40);
server.setExecutor(ForkJoinPool.commonPool());
HttpContext context = server.createContext(SOURCE_FILE_PATH, (HttpExchange he) -> {
String path = he.getRequestURI().getPath();
if (!"GET".equals(he.getRequestMethod()) || !SOURCE_FILE_PATH.equals(path)) {
he.sendResponseHeaders(404, 0);
} else {
Headers headers = he.getResponseHeaders();
headers.add("Content-Type", "application/octet-stream");
headers.add("Content-Disposition", "attachment; filename=\"" + SOURCE_FILE_PATH + "\"");
he.sendResponseHeaders(200, TEST_FILE_SIZE);
try (OutputStream out = he.getResponseBody()) {
out.write(TEST_DATA);
}
}
});
server.start();
InetSocketAddress boundAddresss = server.getAddress();
LOGGER.inform("server", server, "address=" + server.getAddress());
source = new URL("http", boundAddresss.getAddress().getHostAddress(), boundAddresss.getPort(), SOURCE_FILE_PATH);
}
@AfterClass
public static void tearDown() throws Exception {
server.stop(3);
LOGGER.inform("server shutdown");
}
/**
* Test of getInputStream method, of class.
*/
@Test
public void testGetInputStream() throws Exception {
try (InputStream input = source.openConnection().getInputStream()) {
assertNotNull(input);
ByteArrayOutputStream bos = new ByteArrayOutputStream(TEST_FILE_SIZE);
Streams.copy(input, bos);
assertArrayEquals(TEST_DATA, bos.toByteArray());
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment