Micronaut HttpClients exchange body is always null

2k Views Asked by At

I have setup a simple test Controller:

@Controller("/test")
public class SampleController {
  @Get(value = "1", produces = MediaType.TEXT_PLAIN)
  public String helloWorld1() {
    return "Hello, World!";
  }

  @Get(value = "2", produces = MediaType.TEXT_PLAIN)
  public HttpResponse<String> helloWorld2() {
    return HttpResponse.ok("Hello, World!");
  }
}

And I am using the low-level HTTPClient in my Unit-Tests, which looks like this:

@MicronautTest
public class SampleControllerTest {

  @Inject
  EmbeddedServer server;

  @Inject
  @Client("/test")
  HttpClient client;

  @Test
  void shouldReturnHelloWorld1_1() {
    HttpResponse<String> response = client.toBlocking().exchange(HttpRequest.GET("/1").accept(
        MediaType.TEXT_PLAIN));

    assertEquals(200, response.code());
    assertEquals("Hello, World!", response.body());
  }

  @Test
  void shouldReturnHelloWorld1_2() {
    String response = client.toBlocking().retrieve(HttpRequest.GET("/1").accept(MediaType.TEXT_PLAIN));

    assertEquals("Hello, World!", response);
  }

  @Test
  void shouldReturnHelloWorld2() {
    HttpResponse<String> response = client.toBlocking().exchange(HttpRequest.GET("/2").accept(
        MediaType.TEXT_PLAIN));

    assertEquals(200, response.code());
    assertEquals("Hello, World!", response.body());
  }
}

From my understanding the response body should never be null, however it is for the tests shouldReturnHelloWorld2 and shouldReturnHelloWorld1_1 - so it is always null when HttpClient.exchange() is used. In my opinion this seems to be bug or is here any issue?

You can check the whole code and run the tests yourself by cloning my sample repository: https://github.com/tobi6112/micronaut-httpclient-issue

Update: Just noticed that the tests work as expected with

HttpResponse<String> response = client.toBlocking()
        .exchange(HttpRequest.GET("/2").accept(MediaType.TEXT_PLAIN), String.class);
1

There are 1 best solutions below

0
On

In my case these two options work:

final var result = client.toBlocking().exchange(HttpRequest.GET(url).accept(MediaType.APPLICATION_JSON), String.class);

HttpResponse<String> response  = client.toBlocking().exchange(HttpRequest.GET(url).accept(MediaType.APPLICATION_JSON), String.class);