json - Spring Boot 自定义 JSON 序列化器在集成测试中被忽略
问题描述
我有一个 Spring Boot 应用程序,它具有自定义的 Json Serializer/Deserializer,它被注册为这样的 bean:
public class JsonSerializationComponent extends SimpleModule {
public JsonSerializationComponent() {
super("MySerializationModule");
addSerializer(Instant.class, new InstantSerializer());
addDeserializer(Instant.class, new InstantDeserializer());
addSerializer(Hash.class, new HashSerializer());
addDeserializer(Hash.class, new HashDeserializer());
addDeserializer(DateTime.class, new DateTimeDeserializer());
addDeserializer(DMRestVolumeTime.class, new DMRestVolumeTimeDeserializer());
}
}
运行应用程序时,这按预期工作。
问题是当我运行我的集成测试时。我使用 Mock webAppContext 和以下测试设置:
@RunWith(SpringJUnit4ClassRunner.class)
@EnableWebMvc
@WebAppConfiguration
@ContextConfiguration(
classes = {
MyTestConfig.class
},
initializers = {
ConfigDataApplicationContextInitializer.class
})
@ActiveProfiles({"test"})
public class MyIntegrationTest {
@Autowired
private WebApplicationContext webApplicationContext;
private String volumeId;
@Before
public void setup() throws Exception {
this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
}
@Test
public void myTest() throws Exception {
mockMvc.perform(get("/someEndpoint"))
.andDo(print())
.andExpect(status().isOk());
... more testing code here
}
...
}
尽管它是在 Spring 上下文中注册的(使用调试器验证了这一点),但在将响应发送回测试客户端时,spring 控制器不会使用自定义 JSON 序列化器/反序列化器。
我意识到以这种方式设置测试提供了一个简化的 Spring 环境(当使用这个 Mock 设置而不使用时@SpringBootTest
)。我已经这样做了,所以测试运行得更快一点,而且没有太多的内存使用。
如何通过此设置获得测试以使用 JSON 序列化器/反序列化器?这可能吗?
注意:如果我将测试注释更改为:
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes = MyApplication.class)
@WebAppConfiguration
@Import(MyTestConfiguration.class)
@Rollback
@Transactional
正如我所提到的,这会启动一个我试图避免的完整的 spring 应用程序。
解决方案
推荐阅读
- node.js - 如何防止 Apache 服务器和 Node Express 之间的 HTTPS 错误?
- python - 此代码中的.format() 如何工作 [pandas]
- java - Elasticsearch 更新不可搜索
- wordpress - 没有为 wp_nav_menu 申请 container_class
- python - 错误:模块“cv2.cv2”没有属性“STEREO_BM_BASIC_PRESET”
- c++ - 二维数组c ++中元素的出现次数
- python - Matplotlib:如何在 x 对数轴上显示并增加次要和主要刻度的大小
- java - Java、流、收集器、函数式编程:如何制作复式映射?
- php - Laravel hasMany 返回一个空数组或错误
- vba - 打开多个 PowerPoint 文件,导出到视频并关闭文件