我试过这段代码:
//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标记,它的标志是false,然后它的输出应该变成true。现在,在任何情况下,当我尝试使用Intellij执行测试时,我总是获得200状态代码和false作为响应。此外,我得到一条消息:"Token '%7Bid%7D‘not found on database“。但是,如果我尝试使用Postman进行测试,结果正如预期的那样是真的。我的代码出了什么问题?为什么id是“%7Bid%7D”,而不是"c8r1p15dv5lr0on"?"%7Bid%7D“是如何生成的?
我希望我的问题已经说清楚了。
非常感谢!
发布于 2020-01-31 21:47:09
问题解决了。为我效劳:
@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变量连接起来。
https://stackoverflow.com/questions/59989402
复制相似问题