Micronaut 控制器测试 - DefaultHttpClient (RxHttpClient) returns null body 当使用 exchange 而不是 retrive

Micronaut controller test - DefaultHttpClient (RxHttpClient) returns null body when using exchange instead of retrive

这是一个使用 Micronaut 2.3.1 生成的示例应用程序。我有一个简单的控制器和一个 POJO:

@Controller
public class MyController {
    @Get("/hello")
    public HttpResponse<Response> getResponse() {
        return HttpResponse.ok(new Response("Hello"));
    }
}

public class Response {
    private String value;

    private Response() {
    }

    public Response(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }
}

Spock 中的测试套件。问题是当使用 RxHttpClient::exchange 方法时——返回的正文总是 null。但是当使用 RxHttpClient::retrive正文正确返回:

@MicronautTest
class MyControllerTest extends Specification {

    @Inject
    @Client("/")
    RxHttpClient rxHttpClient;

    def "test exchange"() {
        given:

        when:
        HttpResponse<Response> response = rxHttpClient.toBlocking()
                .exchange(HttpRequest.create(HttpMethod.GET, "/hello"))
        then:
        response.status() == HttpStatus.OK
        response.body() != null //fails - body is null
    }

    def "test retrive"() {
        given:

        when:
        Response response = rxHttpClient.toBlocking()
                .retrieve(HttpRequest.create(HttpMethod.GET, "/hello"), Response.class)
        then:
        response != null
        response.value == "Hello"
    }
}

为什么exchange方法返回的HttpResponse的body是null?我想使用它,因为我还想对 HttpResponse.

的其他属性进行断言

这会起作用:

import io.micronaut.http.HttpResponse
import io.micronaut.http.HttpStatus
import io.micronaut.http.client.RxHttpClient
import io.micronaut.http.client.annotation.Client
import io.micronaut.test.extensions.spock.annotation.MicronautTest
import spock.lang.Specification

import javax.inject.Inject

@MicronautTest
class MyControllerSpec extends Specification {

    @Inject
    @Client("/")
    RxHttpClient rxHttpClient;

    void "test exchange"() {
        given:
        HttpResponse response = rxHttpClient.toBlocking().exchange("/hello", Map)
        Map body = response.body()

        expect:
        response.status == HttpStatus.OK
        body.value == 'Hello'
    }
}