问题描述
当在请求生成器中的param()
中传递时,mockmvc会在字符串的末尾添加引号,如下所示
// initialization of mockmvc
mockmvc = mockmvcBuilders.webAppContextSetup(context).build();
ObjectNode tweets = ((ObjectNode) result.getRequest().getAttribute("tweets"));
String query = tweets.get("query").toString();
String nextToken = tweets.get("Meta").get("next_token").toString();
mockmvc.perform(mockmvcRequestBuilders.post("/next")
.param("query",query)
.param("next_token",nextToken)
.accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(jsonPath("$.isError",is("N")))
.andReturn();
如果在控制器中接收到查询为"#GoGreen"
且next_token为"wefw234234ewf234"
查询= "\"#GoGreen\""
和next_token = "\"wefw234234ewf234\""
@PostMapping("/next") @ResponseBody
public ResponseEntity<Object> nextPageTrendingTweets(@RequestParam("query") String query,@RequestParam("next_token") String nextToken)
初始化mockmvc
时可能丢失了某些内容。我搜索了此问题,但找不到任何解决方案。
解决方法
问题不在于嘲笑Mvc,而在于您如何从ObjectNode
“推文”中提取数据。您已经使用.toString()
方法来获取字符串数据。但是,这是不正确的,因为ObjectNode.get()
方法返回对象,而.toString()
将其转换为字符串表示形式,这就是为什么要使用附加引号的原因。因此,解决问题的方法是使用ObjectNode.get().asText()
方法,该方法将在对象中返回该确切的字符串,而无需进行任何修改或转换。
片段部分(#foo
)完全位于浏览器内部,并且未在HTTP请求中传递。完全不要发送。