You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
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<T> { public TestResponse<T> request( final String method, final String path, final String requestBody, final Map<String, String> header, final Class<T> 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<T>(connection.getResponseCode(), body, responseBodyType); } catch (final IOException e) { e.printStackTrace(); fail("Sending request failed: " + e.getMessage()); return null; } }
@Getter @Setter public static class TestResponse<T> {
private final String body; private final int status; private final Class<T> type;
public TestResponse( final int status, final String body, final Class<T> type) { this.status = status; this.body = body; this.type = type; }
public T json() throws IOException { return new ObjectMapper().readValue(body, type); } } }
|