解決方案:這個問題其實是Content-type的問題,只需要在相關的代碼加入相關Content-type中就可以了,代碼如下:
mockMvc.perform(post("/user") // 路徑
.contentType(MediaType.APPLICATION_JSON) //用contentType表示具體請求中的媒體類型信息,MediaType.APPLICATION_JSON表示互聯網媒體類型的json數據格式(見備注)。之前忘記設置了
.content(example)
.accept(MediaType.APPLICATION_JSON)) //accept指定客戶端能夠接收的內容類型
.andExpect(content().contentType("application/json;charset=UTF-8")) //驗證響應contentType == application/json;charset=UTF-8
.andExpect(jsonPath("$.id").value(1)) //驗證id是否為1,jsonPath的使用
.andExpect(jsonPath("$.name).value("kqzhu"); // 驗證name是否等於Zhukeqian
String errorExample = "{"id":1, "name":"kqzhu"}";
MvcResult result = mockMvc.perform(post("/user")
.contentType(MediaType.APPLICATION_JSON)
.content(errorExample)
.accept(MediaType.APPLICATION_JSON)) //執行請求
.andExpect(status().isBadRequest()) //400錯誤請求, status().isOk() 正確 status().isNotFound() 驗證控制器不存在
.andReturn(); //返回MvcResult