本文介紹了如何使用 mockMvc 檢查響應正文中的字符串的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我有簡單的集成測試
@Test
public void shouldReturnErrorMessageToAdminWhenCreatingUserWithUsedUserName() throws Exception {
mockMvc.perform(post("/api/users").header("Authorization", base64ForTestUser).contentType(MediaType.APPLICATION_JSON)
.content("{"userName":"testUserDetails","firstName":"xxx","lastName":"xxx","password":"xxx"}"))
.andDo(print())
.andExpect(status().isBadRequest())
.andExpect(?);
}
在最后一行中,我想將響應正文中收到的字符串與預期的字符串進行比較
In last line I want to compare string received in response body to expected string
作為回應,我得到:
MockHttpServletResponse:
Status = 400
Error message = null
Headers = {Content-Type=[application/json]}
Content type = application/json
Body = "Username already taken"
Forwarded URL = null
Redirected URL = null
用 content()、body() 嘗試了一些技巧,但沒有任何效果.
Tried some tricks with content(), body() but nothing worked.
推薦答案
@Sotirios Delimanolis 回答完成了這項工作,但是我一直在尋找比較這個 mockMvc 斷言中的字符串
@Sotirios Delimanolis answer do the job however I was looking for comparing strings within this mockMvc assertion
原來是這樣
.andExpect(content().string(""Username already taken - please try with different username""));
當然我的斷言失敗了:
java.lang.AssertionError: Response content expected:
<"Username already taken - please try with different username"> but was:<"Something gone wrong">
因為:
MockHttpServletResponse:
Body = "Something gone wrong"
所以這證明它有效!
這篇關于如何使用 mockMvc 檢查響應正文中的字符串的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!