title: Can't manage to test rest template helper class
body: <p>I'm trying for more than an hour to test this class. It went so ugly of stubbing the whole components of the method etc. I'd love some advice how to make a better test or refactor the class to make it way easier to test. I could not figure out a way yet.</p>
  
  <p><strong>Class to Test</strong></p>
  
  <pre><code>@Slf4j
  public final class HistoryRestService {
    static RestTemplate restTemplate = new RestTemplate();
  
    public static Optional&lt;List&lt;History&gt;&gt; findLatestHistories() {
      String url = buildUrl();
      ResponseEntity&lt;History[]&gt; responseEntity = null;
      try {
        responseEntity = restTemplate.getForEntity(url, History[].class);
      } catch (ResourceAccessException e) {
        log.warn("No connection to History persistence. Please check if the history persistence started up properly");
        return Optional.empty();
      }
      History[] histories = responseEntity.getBody();
      return Optional.of(Arrays.asList(histories));
    }
  
    private static String buildUrl() {
      StringBuilder stringBuilder = new StringBuilder();
      stringBuilder.append("http://");
      stringBuilder.append("localhost");
      stringBuilder.append(":8081");
      stringBuilder.append("/history/get");
      return stringBuilder.toString();
    }
  
    // For Testing
    static void setRestTemplate(RestTemplate restTemplate) {
      HistoryRestService.restTemplate = restTemplate;
    }
  }
  </code></pre>
  
  <p><strong>Spock Test which fails</strong></p>
  
  <pre><code>class HistoryRestServiceTest extends Specification {
      def "test findLatestHistories"() {
          given:
          History mockedHistory = Mock()
          HistoryRestService uut = new HistoryRestService()
          History[] expected = [mockedHistory]
          RestTemplate mockedRestTemplate = Stub()
          ResponseEntity&lt;History&gt; mockedResponseEntity = Stub()
  
          mockedResponseEntity.getBody() &gt;&gt; expected
          mockedRestTemplate.getForEntity(_) &gt;&gt; mockedResponseEntity
  
          uut.setRestTemplate(mockedRestTemplate)
  
          when:
          def actual  = uut.findLatestHistories()
          then:
          actual.get() == expected
  
      }
  }
  </code></pre>