【问题标题】:Call a endpoint which return a HashMap with RestTemplate使用 RestTemplate 调用返回 HashMap 的端点
【发布时间】:2017-12-23 13:57:31
【问题描述】:

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

@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。

有什么想法吗?

【问题讨论】:

  • 你能解释一下你的意思吗:“我不能把一个集合作为一个 responseType”?当然可以使用集合(或地图)作为响应类型,例如restTemplate.getForEntity(url, Map.class).getBody()restTemplate.getForObject(url, Map.class)。或许您有可以向我们展示的堆栈跟踪信息?

标签: java spring resttemplate endpoint


【解决方案1】:

如果映射包含不是简单字符串或数字类的对象,getForEntitygetForObject 方法可能无法使用无类型的 Map.class 作为类型正确反序列化映射的对象。在这种情况下,请使用ParameterizedTypeReference,如How to get a generic map as a response from restTemplate exchange method? 中所述。

【讨论】:

    【解决方案2】:

    这里有几种不同的方法似乎都有效...

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

    【讨论】:

    • 由于我没有发现的原因,RANDOM_PORT 似乎在 一些 的情况下工作,其中DEFINED_PORT 失败并出现must be configured with a MockServletContext
    • 关于DEFINED_PORT 遇到的问题我发现的最有趣的提示:stackoverflow.com/a/14443572/86967
    • 注意:将Map 转换为String 以通过添加打印:""+mymap
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    相关资源
    最近更新 更多