简体   繁体   中英

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

This is a sample generated app with Micronaut 2.3.1 . I have a simple controller and a 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;
    }
}

and a test suite in Spock . The problem is that when using RxHttpClient::exchange method - the body returned is always null . However when using RxHttpClient::retrive the body is returned correctly:

@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"
    }
}

Why the body of HttpResponse returned from the exchange method is null? I would like to use it since I also want to make assertions on other properties of HttpResponse .

This will work:

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'
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM