调用一个端点,该端点返回带有 RestTemplate 的 HashMap

3 java spring endpoint 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) {...}` 
Run Code Online (Sandbox Code Playgroud)

我想调用 RestTemplate 进行单元测试。我该如何做到这一点,因为在方法中getForObject我无法将集合作为响应类型。

有什么想法吗?

nob*_*bar 5

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

@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);
    }
}
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

13002 次

最近记录:

5 年,8 月 前