lundi 31 août 2020

Use Spring's TestRestTemplate to test an endpoint that returns a generic type

I'm trying to use Spring's TestRestTemplate to test an endpoint that returns a List<Foo<Bar>>. Currently, the code looks like this:

ResponseEntity<List<Foo<Bar>>> response = this.restTemplate.exchange(
        ApiUrls.GET_FOOS_URL,
        HttpMethod.GET, 
        null,
        new ParameterizedTypeReference<List<Foo<Bar>>>() {});

There ought to be a method available on TestRestTemplate which simplifies calling this endpoint. I've tried using getForEntity instead, e.g.

ResponseEntity<List<Foo<Bar>>> response = this.restTemplate.getForEntity(
        ApiUrls.GET_FOOS_URL, List.class);

But this doesn't compile because List.class doesn't correspond to List<Foo<Bar>> and there's no way I can create a Class object which does (because of type erasure).

Is there a simpler replacement for restTemplate.exchange that I can use in this case which won't generate compiler warnings or require casting?

Aucun commentaire:

Enregistrer un commentaire