简体   繁体   中英

Spring TestRestTemplate POST and PUT not working when adding Netty as a dependency

When adding

    compile 'io.netty:netty-all:4.1.6.Final'

as a dependency to my Spring Boot project all my unit tests using TestRestTemplate.postForObject(...) and TestRestTemplate.put(...) start to fail. It seems the request body isn't transmitted because I get the following error

Failed to read HTTP message:... HttpMessageNotReadableException: Required request body is missing

The service is still working and accepts POST and PUT requests. I checked that using curl. TestRestTemplate.getForObject(...) on the other hand is still working. Using a normal RestTemplate for POST and PUT is also working.

I tried to configure the TestRestTemplate ( right solution, wrong implementation -> see my answer )

@TestConfiguration static class TestConfig { @Bean RestTemplateBuilder restTemplateBuilder() { RestTemplateBuilder restTemplateBuilder = new RestTemplateBuilder() restTemplateBuilder.detectRequestFactory(false) restTemplateBuilder.requestFactory(new SimpleClientHttpRequestFactory()) return restTemplateBuilder } }

with no effect. I also tried to use Netty4ClientHttpRequestFactory which didn't work either. I tried to configure the HttpMessageConverter using the GsonHttpMessageConverter for example... no effect.

TestRestTemplate isn't working because Spring Boot configures it to use Netty4ClientHttpRequestFactory when it finds Netty on the classpath and the Netty4ClientHttpRequestFactory doesn't seem to work.

See https://github.com/spring-projects/spring-boot/issues/7240 and https://jira.spring.io/browse/SPR-14860

To make TestRestTemplate.postForObject(...) and TestRestTemplate.put(...) I had to provide a RestTemplateBuilder @Bean and configure it to use SimpleClientHttpRequestFactory . The RestTemplateBuilder @Bean in the question has a few errors. It's supposed to look like this

@TestConfiguration
static class TestConfig {
    @Bean
    public RestTemplateBuilder restTemplateBuilder() {
        return new RestTemplateBuilder().detectRequestFactory(false).requestFactory(SimpleClientHttpRequestFactory.class);
    }
}

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