title: How do I unit test a Spring RestTemplate that takes a ResponseExtractor and RequestCallback?
body: <p>I am developing in Groovy and I am trying to write a Spock unit test for the following use of Spring's RestTemplate...</p>
  
  <p>Included are my request callback and response extractors, and my initialization class of the RestTemplate bean. I am using the ResponseExtractor to stream the response from <code>GET myurl/</code> and copy it to a file. The RequestCallback is simply setting some headers on the request.</p>
  
  <pre><code>class RestTemplateConfig() {
    @Bean(name = 'myRestTemplate')
    RestTemplate getMyRestTemplate() {
      RestTemplate restTemplate = new RestTemplateBuilder().build()
      return restTemplate
    }
  }
  
  class MyClass() {
  
    @Autowired
    @Qualifier('myRestTemplate')
    RestTemplate restTemplate
  
    File getFile() {
  
       ResponseExtractor&lt;Void&gt; responseExtractor = { ClientHttpResponse response -&gt;
         // do something with the response
         // in this case, the response is an input stream so we copy the input stream to a file
         myFile = response.getBody() // roughly, in a psuedocode-ish way
         return null
       }
  
       RequestCallback requestCallback = { ClientHttpRequest request -&gt;
         request.getHeaders().setAccept([MediaType.APPLICATION_JSON])
       }
  
       File myFile
       // get my file data
       restTemplate.execute('myurl/', HttpMethod.GET, requestCallback, responseExtractor)
       return myFile
    }
  }
  </code></pre>
  
  <p>Spring framework docs for that particular <code>execute(...)</code> method: <a href="https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#execute-java.net.URI-org.springframework.http.HttpMethod-org.springframework.web.client.RequestCallback-org.springframework.web.client.ResponseExtractor-" rel="nofollow noreferrer">https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#execute-java.net.URI-org.springframework.http.HttpMethod-org.springframework.web.client.RequestCallback-org.springframework.web.client.ResponseExtractor-</a></p>
  
  <p>How do I mock out what's happening in these closures? Specifically, I'm interested in mocking out my response extractor because my current test always returns <code>myFile</code> as null. </p>
  
  <pre><code>    when:
      // do stuff
  
      then:
      1 * restTemplate.execute('myurl/, HttpMethod.GET, _, _) // how can I mock out the expected response here?
      0 * _
  
      myFile != null // this fails because myFile is null
  
  </code></pre>