我有一个带有以下签名的端点
@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。
任何想法?
答案 0 :(得分:1)
如果映射包含的对象不是简单的字符串或数字类,则getForEntity
和getForObject
方法可能无法使用未类型化的Map.class
作为类型来正确反序列化映射的对象。在这种情况下,请按How to get a generic map as a response from restTemplate exchange method?中所述使用ParameterizedTypeReference
。
答案 1 :(得分:0)
以下是一些似乎都有效的方法......
@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);
}
}