【问题标题】:Test method issue测试方法问题
【发布时间】:2020-01-30 15:32:47
【问题描述】:

我试过这段代码:

//CONTROLLER


@GetMapping(path = "/validateToken/{id}")
public ResponseEntity<Boolean> validateToken(@PathVariable String id) {
        try {
            boolean bool=webSSOService.validateToken(id);
            return new ResponseEntity<Boolean>(bool, HttpStatus.OK);
        } catch (Exception e) {
            LOGGER.error(Message.ERROR_OCCURRED+Thread.currentThread().getStackTrace()[1].getMethodName()+": "+ e.getMessage());
            if (LOGGER.isDebugEnabled()) {
                e.printStackTrace();
            }
            return new ResponseEntity<Boolean>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
}
//SERVICE

@Override
public boolean validateToken(String id) throws JsonProcessingException {
        Map<String,Object> parameters=new HashMap<>();
        parameters.put("id",id);

        String uri="/SSOServiceToken/validateToken/{id}";
        HttpMethod httpMethod=HttpMethod.GET;

        boolean bool=executeFilteredRequest(parameters,uri,Boolean.class,httpMethod);
        return bool;
}

private <T> T executeFilteredRequest(Map<String,Object> parameters, String uri, Class<T> type, HttpMethod httpMethod) throws JsonProcessingException {
        RestTemplate restTemplate = restTemplateBuilder.build();

        HttpHeaders headers = new HttpHeaders();
        headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
        headers.setContentType(MediaType.APPLICATION_JSON);

        UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl("http://localhost:8180" + uri);
        String jsonBody=""; 

        if (httpMethod == HttpMethod.POST){
            ObjectMapper objectMapper=new ObjectMapper();
            jsonBody=objectMapper.writeValueAsString(parameters); 
        }else{
            parameters.forEach( (key, value) -> builder.queryParam(key,value));
        }
        HttpEntity<?> entity = new HttpEntity<>(jsonBody,headers); 

        ResponseEntity<T> response = restTemplate.exchange(builder.toUriString(),
                                                           httpMethod,
                                                           entity,
                                                           type);

        return response.getBody();
    }

那我要测试validateToken:

 @Test
 public void validateTokenIsOk() throws Exception {

        mockMvc.perform(MockMvcRequestBuilders
                .get("/validateToken/{id}","c8r1p15dv5lr0on")
                .accept(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk());
 }

方法 validateToken 接受一个 id Token,它的标志是 false,在输入中,然后它的输出应该变为 true。 现在,在任何情况下,当我尝试使用 Intellij 执行测试时,我总是获得 200 状态代码和 false 作为响应。此外,我收到一条消息:“在数据库中找不到令牌 '%7Bid%7D'”。 但是,如果我尝试使用 Postman 进行测试,结果正如预期的那样是正确的。 我的代码有什么问题?为什么 id 是“%7Bid%7D”,而不是“c8r1p15dv5lr0on”? “%7Bid%7D”是如何产生的?

我希望我的问题很清楚。

非常感谢!

【问题讨论】:

    标签: spring-mvc mockito


    【解决方案1】:

    问题解决了。在我的服务中:

    @Override
    public boolean validateToken(String id) throws JsonProcessingException {
    
            Map<String,Object> parameters=new HashMap<>();
    
            String uri="/SSOServiceToken/validateToken"+id;
            .
            .
            .
    

    “%7Bid%7D”字符串是 uri 变量中“{id}”的编码字符串。所以,为了避免那个虚假的字符串,我需要将我的 uri 与 id 变量连接起来。

    【讨论】:

      猜你喜欢
      • 2020-07-13
      • 2021-11-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 1970-01-01
      • 2012-04-07
      相关资源
      最近更新 更多