package de.fd.fh.server; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.Getter; import lombok.Setter; import spark.utils.IOUtils; import java.io.IOException; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.net.HttpURLConnection; import java.net.URL; import java.nio.charset.StandardCharsets; import java.util.Map; import static org.junit.jupiter.api.Assertions.fail; public class ApiTestUtils { public TestResponse request( final String method, final String path, final String requestBody, final Map header, final Class responseBodyType) { try { URL url = new URL("http://localhost:4567" + path); final HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod(method); connection.setDoOutput(true); if (requestBody != null) { final OutputStream outputStream = connection.getOutputStream(); final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); outputStreamWriter.write(requestBody); outputStreamWriter.flush(); outputStreamWriter.close(); } if (header != null) { header.forEach(connection::addRequestProperty); } connection.connect(); final String body = IOUtils.toString(connection.getInputStream()); return new TestResponse(connection.getResponseCode(), body, responseBodyType); } catch (final IOException e) { e.printStackTrace(); fail("Sending request failed: " + e.getMessage()); return null; } } @Getter @Setter public static class TestResponse { private final String body; private final int status; private final Class type; public TestResponse( final int status, final String body, final Class type) { this.status = status; this.body = body; this.type = type; } public T json() throws IOException { return new ObjectMapper().readValue(body, type); } } }