我已經寫了一個小測試Spring REST文檔與自定義傑克遜模塊(使用Spring Boot 1.3)。在我的應用程序主類中,我只有@SpringBootApplication
。然後,我有另一個類JacksonCustomizations
,看起來像這樣:自定義傑克遜模塊不使用在春季REST文檔測試
@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());
}
});
}
}
}
這種定製是完全回升。當我運行Spring Boot應用程序時,我看到它應該是JSON。
但是,在我的文檔測試中,自定義不適用。這是我的測試代碼:
@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();
}
}
}
注意如何在我的測試應用程序上下文進口JacksonCustomizations
配置。
其他的事情,我發現:
- 添加在我的引導應用
@EnableWebMvc
從工作停止定製。 - 在我的測試中刪除
@EnableWebMvc
將停止生成JSON。
您是否嘗試添加@Import(JacksonCustomizations.class)到NoteControllerDocumentation類? – reos
@reos並沒有區別 –
這聽起來像Spring Boot沒有自動配置'ObjectMapper'與您的自定義'模塊'。這符合你沒有爲你的應用程序提供'SpringApplicationConfiguration'類的事實,所以Spring Boot不知道該怎麼做。實際上,您共享的代碼由於這個原因而失敗,並且出現「IllegalStateException」,其中顯示「沒有在@SpringApplicationConfiguration中找到配置類或位置」。您是否可以分享一個小樣本項目,其中包含您正在運行的確切代碼以觸發問題? –