Test method issue

34 views Asked by At

I tried this code:

//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();
    }

Then I have to test validateToken:

 @Test
 public void validateTokenIsOk() throws Exception {

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

The method validateToken takes an id Token, which its flag is false, in input, and then its output should become true. Now, I always obtain a 200 status code and false as response, in every case, when I try to perform the test with Intellij. Furthermore, I obtain a message: "Token '%7Bid%7D' not found on database". But if I try to test with Postman, result is true as expected. What's wrong with my code? Why is the id"%7Bid%7D", instead of "c8r1p15dv5lr0on"? How is "%7Bid%7D" generated?

I hope I was clear in my question.

Thank you very much!

1

There are 1 answers

0
Nivel23 On

Problem solved. In my service:

@Override
public boolean validateToken(String id) throws JsonProcessingException {

        Map<String,Object> parameters=new HashMap<>();

        String uri="/SSOServiceToken/validateToken"+id;
        .
        .
        .

That "%7Bid%7D" string was an encoded one of "{id}" in uri variable. So, in order to avoid that spurious string, I need to concatenate my uri with id variable.