2

I have a endpoint with the below signature

@RequestMapping(method = RequestMethod.GET, value = "/{id}", produces = {"application/json; charset=UTF-8"})
@Transactional(readOnly = true)
@ResponseBody
public HashMap<String, Object> myMethod(@PathVariable("id") Long id) {...}` 

And I want to make a call with RestTemplate for unit testing. How I can do that because in method getForObject I can't put a collection as a responseType.

Any ideea?

  • Possible duplicate of [resttemplate getForObject map responsetype](https://stackoverflow.com/questions/24208828/resttemplate-getforobject-map-responsetype) – Zico Jul 18 '17 at 16:22
  • 1
    Can you explain what you mean this this: "I can't put a collection as a responseType"? It is certainly possible to use a collection (or a Map) as a response type e.g. `restTemplate.getForEntity(url, Map.class).getBody()`, `restTemplate.getForObject(url, Map.class)`. Perhaps you have a stack trace you can show us? – glytching Jul 18 '17 at 16:59

2 Answers2

4

Here are a few different methods that all seem to work...

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT)
public class MyTests {

    @LocalServerPort private int port;
    @Autowired private TestRestTemplate restTemplate;

    @Test
    public void healthCheck() {
        String url = "http://localhost:" + port + "/actuator/health";

    //  choose one of the following...
        ResponseEntity<JsonNode> e = restTemplate.getForEntity(url,JsonNode.class);
        Map<String,Object> b = restTemplate.getForObject(url,Map.class);
        Map b = restTemplate.getForObject(url,Map.class);
        ResponseEntity<Map> e = restTemplate.getForEntity(url,Map.class);

        System.out.println("entity: "+e);
        System.out.println("body: "+b);
    }
}
Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173
1

If the map contains objects that aren't simple strings or number classes, getForEntity and getForObject methods may not deserialize the mapped objects correctly using the untyped Map.class as the type. In that case, use ParameterizedTypeReference as described in How to get a generic map as a response from restTemplate exchange method?.

landonvg
  • 41
  • 1
  • 7