【问题标题】:Using RestTemplate in Spring Boot Spock specification with customized Jackson在 Spring Boot Spock 规范中使用带有自定义 Jackson 的 RestTemplate
【发布时间】: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


    【解决方案1】:

    使用 spock-spring 提供的 Spock 的 Spring 支持,您可以将 ObjectMapper 注入到您的测试规范中:

    @WebIntegrationTest
    @ContextConfiguration(loader = SpringApplicationContextLoader, classes = MyApplication)
    class SomeTestSpec extends Specification {
    
        @Autowired
        ObjectMapper objectMapper
    
    }
    

    【讨论】:

    • 让 RestTemplate 在内部使用该映射器的最佳方法是什么?
    • 使用ObjectMapper 创建MappingJackson2HttpMessageConverter 并配置您的RestTemplate 以使用转换器
    猜你喜欢
    • 2017-01-08
    • 2020-07-03
    • 2020-05-20
    • 1970-01-01
    • 2016-12-11
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 2014-09-03
    相关资源
    最近更新 更多