title: Using RestTemplate in Spring Boot Spock specification with customized Jackson
body: <p>I have a Spring Boot app that's using a customized Jackson ObjectMapper, and I would like to use the same customized mapper during testing. I used spring boot's method of automatically registering Module Beans, like this:</p>
  
  <pre><code>@Configuration
  public class JacksonConfig {
      @Bean
      public Module jodaMoneyJackson() {
          SimpleModule jodaMoneyModule = new SimpleModule();
  
          jodaMoneyModule.addDeserializer(Money.class, new JsonDeserializer&lt;Money&gt;() {
              @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();
      }
  }
  </code></pre>
  
  <p>In my spock tests I would like RestTemplate to use the "built-in" Jackson object mapper that automatically registers the custom modules. In the actual app it seems like that's just used automatically, but not in my test classes. How can I make it work for my tests?</p>
  
  <p>Here's roughly what my test spec looks like:</p>
  
  <pre><code>@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
      }
  }
  </code></pre>
  
  <p>I always get a 400 Bad Request response with this, and when debugging I can see that it's because internally the serialization/deserialization isn't using my custom module.</p>
  
  <p>As as workaround I have instantiated my own object mapper and am registering the modules manually, then calling mapper.readValue() with a String response from RestTemplate, but it feels like there should be a better way. Any input would be appreciated.</p>