【发布时间】:2015-07-03 19:55:45
【问题描述】:
我有一个使用自定义 Jackson ObjectMapper 的 Spring Boot 应用程序,我想在测试期间使用相同的自定义映射器。我使用了spring boot的自动注册Module Bean的方法,如下:
@Configuration
public class JacksonConfig {
@Bean
public Module jodaMoneyJackson() {
SimpleModule jodaMoneyModule = new SimpleModule();
jodaMoneyModule.addDeserializer(Money.class, new JsonDeserializer<Money>() {
@Override
public Money deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
return Money.parse(p.getText());
}
});
jodaMoneyModule.addSerializer(Money.class, new ToStringSerializer());
return jodaMoneyModule;
}
@Bean public Module googleGuavaJackson() {
return new GuavaModule();
}
}
在我的 spock 测试中,我希望 RestTemplate 使用自动注册自定义模块的“内置”Jackson 对象映射器。在实际的应用程序中,它似乎只是自动使用的,但不是在我的测试类中。如何使它适用于我的测试?
我的测试规范大致如下所示:
@WebIntegrationTest
@ContextConfiguration(loader = SpringApplicationContextLoader, classes = MyApplication)
class SomeTestSpec extends Specification {
def restTemplate = new RestTemplate()
def "test my controller"() {
given:
Money expectedTotal = Money.of(CurrencyUnit.USD, 100.00)
String request = this.class.classLoader.getResource("testInput.json").text
when:
def response = restTemplate.postForObject("http://localhost:8080/test", request, SomeClass)
then:
response.total == expectedTotal
}
}
我总是收到 400 Bad Request 响应,调试时我可以看到这是因为内部序列化/反序列化没有使用我的自定义模块。
作为解决方法,我已经实例化了自己的对象映射器并手动注册了模块,然后使用来自 RestTemplate 的字符串响应调用 mapper.readValue(),但感觉应该有更好的方法。任何意见将不胜感激。
【问题讨论】:
标签: spring-mvc spring-boot spock spring-test-mvc