Micronaut HttpClients 的交换体始终为 null

6

我已经设置了一个简单的测试控制器:

@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!");
  }
}

我在单元测试中使用低级别的HTTPClient,代码如下:

@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());
  }
}

据我所知,响应正文应该永远不会是 null,但是对于测试“shouldReturnHelloWorld2”和“shouldReturnHelloWorld1_1”,它确实是 null - 因此在使用“HttpClient.exchange()”时总是为 null。我认为这似乎是一个错误或者有问题吗?
您可以通过克隆我的示例存储库 https://github.com/tobi6112/micronaut-httpclient-issue 来检查整个代码并运行测试。
更新: 刚刚注意到,测试与预期一样工作。
HttpResponse<String> response = client.toBlocking()
        .exchange(HttpRequest.GET("/2").accept(MediaType.TEXT_PLAIN), String.class);

我建议您使用断点检查专用控制器函数是否按预期调用,也许这可以帮助您。 - IEE1394
1
据我理解,响应体不应该为null。但是,https://docs.micronaut.io/2.5.4/api/io/micronaut/http/HttpResponse.html#body--上的文档表明,该方法返回“正文或null”。 - Jeff Scott Brown
您所做的对问题的修改应该使.body()方法返回非空。 - Jeff Scott Brown
@JeffScottBrown,是的,那个工作非常好。但是根据BlockingHttpClient的文档https://docs.micronaut.io/2.1.3/api/io/micronaut/http/client/BlockingHttpClient.html#exchange-io.micronaut.http.HttpRequest-参数不应该是必需的,因为它可以从`HttpResponse`的泛型类型中推断出来。也许我错了,但这是我从文档中期望的。 - twobiers
1个回答

0

在我的情况下,这两个选项都可以使用:

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);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接