首页 > 解决方案 > 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 应用程序。

标签: jsonspringspring-bootspring-testspring-test-mvc

解决方案


推荐阅读