I've created a Spring Boot v4.0.0-M3 app that reproduces an issue with the new TestRestClient
. To reproduce the issue
- Clone the app, be sure to use the
rest-test-client-spring-v4.0.0-m3
branch - Run the tests in ItemControllerTests
This class has two tests
parseResponseAsApiErrorResponse
calls an endpoint and parses the response to aApiErrorResponse
parseResponseAsString
calls an endpoint, parses the response body as aString
then converts that to anApiErrorResponse
viaobjectMapper.readValue(responseBody, ApiErrorResponse.class)
The first test fails, but the second one passes, because only the second test calls the custom deserializer ApiErrorResponseDeserializer
.
Why is the custom serializer ignored by the first test?
Comment From: wilkinsona
You've created the RestTestClient
in your own configuration and haven't configured it to use the JsonMapper
from the context. As such, it doesn't know anything about your custom JSON configuration. To get it to work, it would have to be set up with a JacksonJsonHttpMessageConverter
that's using the context's JsonMapper
.
Built-in support for RestTestClient
is coming in 4.0.0-RC1, although I think it may be missing this customisation too. I'll re-open #47335 so that we can double-check.
Comment From: donalmurtagh
@wilkinsona thanks for your reply. I made a change to the RestTestClient
bean initialization based on your feedback and now the test that parses the response body to an ApiErrorResponse
passes.
Curiously, the test that parses the ressponse body to a String (which was previously passing), now fails with the error:
JSON parse error: Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
org.springframework.http.converter.HttpMessageNotReadableException: JSON parse error: Cannot deserialize value of type `java.lang.String` from Object value (token `JsonToken.START_OBJECT`)
at app//org.springframework.http.converter.AbstractJacksonHttpMessageConverter.readJavaType(AbstractJacksonHttpMessageConverter.java:366)
at app//org.springframework.http.converter.AbstractJacksonHttpMessageConverter.read(AbstractJacksonHttpMessageConverter.java:322)
at app//org.springframework.web.client.DefaultRestClient.readWithMessageConverters(DefaultRestClient.java:245)
at app//org.springframework.web.client.DefaultRestClient$DefaultConvertibleClientHttpResponse.bodyTo(DefaultRestClient.java:955)
at app//org.springframework.test.web.servlet.client.DefaultRestTestClient$DefaultResponseSpec.expectBody(DefaultRestTestClient.java:289)
at app//com.example.demo.ItemControllerTests.parseResponseAsString(ItemControllerTests.java:42)