|
| 1 | +package io.securecodebox.persistence.defectdojo; |
| 2 | + |
| 3 | +import com.github.tomakehurst.wiremock.junit5.WireMockRuntimeInfo; |
| 4 | +import com.github.tomakehurst.wiremock.junit5.WireMockTest; |
| 5 | +import org.junit.jupiter.api.Test; |
| 6 | + |
| 7 | +import java.io.IOException; |
| 8 | +import java.net.URI; |
| 9 | +import java.net.http.HttpClient; |
| 10 | +import java.net.http.HttpRequest; |
| 11 | +import java.net.http.HttpResponse; |
| 12 | + |
| 13 | +import static com.github.tomakehurst.wiremock.client.WireMock.*; |
| 14 | +import static org.hamcrest.MatcherAssert.assertThat; |
| 15 | +import static org.hamcrest.Matchers.containsString; |
| 16 | +import static org.hamcrest.Matchers.is; |
| 17 | + |
| 18 | +/** |
| 19 | + * This is just a PoC to test if WireMock is sufficient to test our REST calls |
| 20 | + * <p> |
| 21 | + * See https://wiremock.org/docs/quickstart/java-junit/ |
| 22 | + * and https://wiremock.org/docs/junit-jupiter/ |
| 23 | + */ |
| 24 | +@WireMockTest(httpPort = HttpClientTest.PORT) |
| 25 | +final class HttpClientTest { |
| 26 | + |
| 27 | + public static final int PORT = 8888; |
| 28 | + |
| 29 | + private URI createUri(String path) { |
| 30 | + return URI.create("http://localhost:%d/%s".formatted(PORT, path)); |
| 31 | + } |
| 32 | + |
| 33 | + @Test |
| 34 | + void test_something_with_wiremock(WireMockRuntimeInfo wmRuntimeInfo) throws IOException, InterruptedException { |
| 35 | + stubFor(get("/my/resource") |
| 36 | + .withHeader("Content-Type", containing("xml")) |
| 37 | + .willReturn(ok() |
| 38 | + .withHeader("Content-Type", "text/xml") |
| 39 | + .withBody("<response>SUCCESS</response>"))); |
| 40 | + |
| 41 | + // Setup HTTP POST request (with HTTP Client embedded in Java 11+) |
| 42 | + final HttpClient client = HttpClient.newBuilder().build(); |
| 43 | + final HttpRequest request = HttpRequest.newBuilder() |
| 44 | + .uri(createUri("my/resource")) |
| 45 | + .header("Content-Type", "text/xml") |
| 46 | + .GET() |
| 47 | + .build(); |
| 48 | + |
| 49 | + // Send the request and receive the response |
| 50 | + final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString()); |
| 51 | + |
| 52 | + // Verify the response (with AssertJ) |
| 53 | + assertThat(response.statusCode(), is(200)); |
| 54 | + assertThat(response.body(), containsString("<response>SUCCESS</response>")); |
| 55 | + } |
| 56 | +} |
0 commit comments