From 5078dd614629b3f8ef74dd633086590b5732d8f9 Mon Sep 17 00:00:00 2001 From: Sven Strittmatter Date: Fri, 1 Mar 2024 21:29:09 +0100 Subject: [PATCH] Add Basic Setup to Write Tests for hTTP Client We do lot of HTTP client calls, but do not have much tests about that. This is the foundation to write capture replay test for the DefectDojo API calls. Signed-off-by: Sven Strittmatter --- pom.xml | 6 ++ .../defectdojo/HttpClientTest.java | 56 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 src/test/java/io/securecodebox/persistence/defectdojo/HttpClientTest.java diff --git a/pom.xml b/pom.xml index 3f25857f..e9c17ac0 100644 --- a/pom.xml +++ b/pom.xml @@ -178,6 +178,12 @@ 3.15.6 test + + org.wiremock + wiremock + 3.4.1 + test + diff --git a/src/test/java/io/securecodebox/persistence/defectdojo/HttpClientTest.java b/src/test/java/io/securecodebox/persistence/defectdojo/HttpClientTest.java new file mode 100644 index 00000000..af8dbdee --- /dev/null +++ b/src/test/java/io/securecodebox/persistence/defectdojo/HttpClientTest.java @@ -0,0 +1,56 @@ +package io.securecodebox.persistence.defectdojo; + +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; +import com.github.tomakehurst.wiremock.junit5.WireMockTest; +import org.junit.jupiter.api.Test; + +import java.io.IOException; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; + +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.hamcrest.Matchers.containsString; +import static org.hamcrest.Matchers.is; + +/** + * This is just a PoC to test if WireMock is sufficient to test our REST calls + *

+ * See https://wiremock.org/docs/quickstart/java-junit/ + * and https://wiremock.org/docs/junit-jupiter/ + */ +@WireMockTest(httpPort = HttpClientTest.PORT) +final class HttpClientTest { + + public static final int PORT = 8888; + + private URI createUri(String path) { + return URI.create("http://localhost:%d/%s".formatted(PORT, path)); + } + + @Test + void test_something_with_wiremock(WireMockRuntimeInfo wmRuntimeInfo) throws IOException, InterruptedException { + stubFor(get("/my/resource") + .withHeader("Content-Type", containing("xml")) + .willReturn(ok() + .withHeader("Content-Type", "text/xml") + .withBody("SUCCESS"))); + + // Setup HTTP POST request (with HTTP Client embedded in Java 11+) + final HttpClient client = HttpClient.newBuilder().build(); + final HttpRequest request = HttpRequest.newBuilder() + .uri(createUri("my/resource")) + .header("Content-Type", "text/xml") + .GET() + .build(); + + // Send the request and receive the response + final HttpResponse response = client.send(request, HttpResponse.BodyHandlers.ofString()); + + // Verify the response (with AssertJ) + assertThat(response.statusCode(), is(200)); + assertThat(response.body(), containsString("SUCCESS")); + } +}