我已经设置了一个简单的测试控制器:
@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);
.body()
方法返回非空。 - Jeff Scott Brown