使用 RestTemplate 调用 return 一个 HashMap 的端点

Call a endpoint which return a HashMap with RestTemplate

我有一个具有以下签名的端点

@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) {...}` 

我想调用 RestTemplate 进行单元测试。我该怎么做,因为在方法 getForObject 中我无法将集合作为 responseType。

有什么想法吗?

这里有一些似乎都有效的不同方法...

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

如果映射包含不是简单字符串或数字的对象 类,getForEntitygetForObject 方法可能无法使用非类型化 [=12= 正确反序列化映射对象] 作为类型。在这种情况下,请按照 .

中所述使用 ParameterizedTypeReference