All
I have customized Jackson2ObjectMapperBuilder in my main Spring Boot application class as below.
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Autowired
public void configureJackson(Jackson2ObjectMapperBuilder builder) {
builder.filters( new SimpleFilterProvider().addFilter( "customFilter", new ExampleFilter() ) );
}
where ExampleFilter is an extension of SimpleBeanPropertyFilter.
My POJOs are annotated with Jackson's @JsonFilter("customFilter").
I have exposed the POJOs over HTTP using @RestController and @GetMapping annotations.
This works fine and the custom filter gets invoked when I run the application and access the end point.
Now I have an integration test written as below.
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class IntegrationTest {
@LocalServerPort
private int port;
@Autowired
private TestRestTemplate restTemplate;
@Test
public void getUser() throws Exception {
POJO obj = this.restTemplate.getForObject("http://localhost:" + this.port + "/pojo", POJO.class);
Assertions.assertThat(obj).isNotNull();
Assertions.assertThat(obj.getFirstName()).isEqualTo("Jane");
Assertions.assertThat(obj.getLastName()).isEqualTo("Doe");
Assertions.assertThat(obj.getAge()).isEqualTo("24");
}
}
When I run the test, the obj comes as null and I see an error that no FilterProvider configured
Failed to write HTTP message: org.springframework.http.converter.HttpMessageNotWritableException: Could not write content: Can not resolve PropertyFilter with id 'customFilter'; no FilterProvider configured; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not resolve PropertyFilter with id 'customFilter'; no FilterProvider configured
What am I doing wrong and how do I correct this?
My folder structure is :
src/main/java/com/a/b/c/Application.java
src/main/java/com/a/b/c/controller/ControllerA.java
src/test/java/com/a/b/c/controller/IntegrationTest.java
I got this working by configuring Jackson2ObjectMapperBuilder in a slightly different way in the main application file as shown below. But I still don't know why the Autowiring approach isn't working.
@Bean
public Jackson2ObjectMapperBuilder objectMapperBuilder() {
Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
builder.filters( new SimpleFilterProvider().addFilter( "customFilter", new ExampleFilter() ) );
return builder;
}
I'd still like to know that in the test context, why the auto configured Jackson2ObjectMapperBuilder isn't picked up for customization while replacing it with @Bean works.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With