I have written a small test on Spring REST docs with custom Jackson module (using Spring Boot 1.3). In my application main class, I only have @SpringBootApplication
. I then have another class JacksonCustomizations
that looks like this:
@Configuration
public class JacksonCustomizations {
@Bean
public Module myCustomModule() {
return new MyCustomModule();
}
static class MyCustomModule extends SimpleModule {
public MyCustomModule() {
addSerializer(ImmutableEntityId.class, new JsonSerializer<ImmutableEntityId>() {
@Override
public void serialize(ImmutableEntityId immutableEntityId, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException, JsonProcessingException {
jsonGenerator.writeNumber( (Long)immutableEntityId.getId() );
}
});
}
}
}
This customization is picked up perfectly. When I run the Spring Boot application, I see the JSON as it should be.
However, in my documentation test, the customization is not applied. This is the code of my test:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration
@WebAppConfiguration
public class NoteControllerDocumentation {
@Rule
public final RestDocumentation restDocumentation = new RestDocumentation("target/generated-snippets");
@Autowired
private WebApplicationContext context;
private MockMvc mockMvc;
@Before
public void setUp() throws Exception {
mockMvc = MockMvcBuilders.webAppContextSetup(context)
.apply(documentationConfiguration(restDocumentation))
.build();
}
@Test
public void notesListExample() throws Exception {
mockMvc.perform(get("/api/notes/"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
.andDo(document("notes-list-example", responseFields(
fieldWithPath("[]").description("An array of <<note-example,note>>s."))));
}
@Configuration
@EnableWebMvc
@Import(JacksonCustomizations.class)
public static class TestConfiguration {
@Bean
public NoteController noteController() {
return new NoteController();
}
}
}
Note how the application context in my test imports the JacksonCustomizations
configuration.
Other things I found:
- Adding
@EnableWebMvc
on my boot application stops the customization from working. - Removing the
@EnableWebMvc
on my test stops JSON being produced.