MockServer unexpectedly responds with empty body

2.2k views Asked by At

Let's see a test, which is using MockServer (org.mock-server:mockserver-netty:5.10.0) for mocking responses.

It is expected that the response body will be equal to string "something". Nevertheless, this test fails, because the response body is an empty string.

  @Test 
  void test1() throws Exception {

    var server = ClientAndServer.startClientAndServer(9001);

    server
        .when(
            request().withMethod("POST").withPath("/checks/"),
            exactly(1)
        )
        .respond(
            response()
                .withBody("\"something\"")
                .withStatusCode(205)
                .withHeader("Content-Type", "application/json")
        );

    HttpRequest request = HttpRequest.newBuilder()
                                     .uri(URI.create("http://localhost:9001/checks/"))
                                     .POST(BodyPublishers.noBody())
                                     .build();

    HttpResponse<String> response =
        HttpClient.newHttpClient().send(request, BodyHandlers.ofString());

    assertEquals(205, response.statusCode());
    assertEquals("something", response.body()); // fails
  }

How to make the response body be equal to the string provided in response().withBody(...)?

1

There are 1 answers

0
diziaq On BEST ANSWER

The problem is on the client side. It drops content.

Why!?

Because, HTTP 205 is RESET_CONTENT. This status was chosen accidentally for test as "somenthing different from HTTP 200", and unfortunately caused this behaviour. Looks like it is very popular "accidental" mistake (i.e. here), although it is strictly in accordance with the HTTP spec.