wiremock / wiremock.org

WireMock website, powered by Jekyll. Contributions are welcome!
https://wiremock.org/
MIT License
11 stars 50 forks source link

Issue on Quick Start: API Mocking with Java and JUnit 4 #307

Open SiKing opened 3 months ago

SiKing commented 3 months ago

Page

/docs/quickstart/java-junit/

Details

After copy/pasting the code. I get a compile error: wiremockServer cannot be resolved

I tried to change wiremockServer.url("/my/resource") to URI.create(wireMockRule.url("/my/resource")), but then I got: The method POST(HttpRequest.BodyPublisher) in the type HttpRequest.Builder is not applicable for the arguments ()

Suggested Edits

No response

References

No response

SiKing commented 3 months ago

Eventually something like this worked for me:

    @Test
    public void exampleTest() throws Exception {
    // Setup the WireMock mapping stub for the test
    stubFor(get("/my/resource").withHeader("Content-Type", containing("xml"))
        .willReturn(ok().withHeader("Content-Type", "text/xml").withBody("<response>SUCCESS</response>")));

    // Setup HTTP **GET** request (with HTTP Client embedded in Java 11+)
    final HttpClient client = HttpClient.newBuilder().build();
    final HttpRequest request = HttpRequest.newBuilder().uri(URI.create(wireMockRule.url("/my/resource")))
        .header("Content-Type", "text/xml").GET().build();

    // Send the request and receive the response
    final HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

    // Verify the response (with AssertJ)
    assertThat(response.statusCode()).as("Wrong response status code").isEqualTo(200);
    assertThat(response.body()).as("Wrong response body").contains("<response>SUCCESS</response>");
    }