mardi 12 décembre 2017

Can't manage to test rest template helper class

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.

Class to Test

@Slf4j
public final class HistoryRestService {
  static RestTemplate restTemplate = new RestTemplate();

  public static Optional<List<History>> findLatestHistories() {
    String url = buildUrl();
    ResponseEntity<History[]> 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;
  }
}

Spock Test which fails

class HistoryRestServiceTest extends Specification {
    def "test findLatestHistories"() {
        given:
        History mockedHistory = Mock()
        HistoryRestService uut = new HistoryRestService()
        History[] expected = [mockedHistory]
        RestTemplate mockedRestTemplate = Stub()
        ResponseEntity<History> mockedResponseEntity = Stub()

        mockedResponseEntity.getBody() >> expected
        mockedRestTemplate.getForEntity(_) >> mockedResponseEntity

        uut.setRestTemplate(mockedRestTemplate)

        when:
        def actual  = uut.findLatestHistories()
        then:
        actual.get() == expected

    }
}

Aucun commentaire:

Enregistrer un commentaire