Search code examples
javaspringresttemplateendpoint

Call a endpoint which return a HashMap with RestTemplate


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?


Solution

  • 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);
        }
    }