0

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(...)?

diziaq
  • 6,881
  • 16
  • 54
  • 96
  • Maybe the problem is that `"something"` isn't valid JSON, as you claim with the Content-Type? In addition, should it be `"\"something\""` - though you say that the body is empty. – bimmlerd Nov 10 '20 at 09:18
  • string is a valid JSON by definition – diziaq Nov 10 '20 at 09:22

1 Answers1

1

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.

diziaq
  • 6,881
  • 16
  • 54
  • 96