我正在使用MockMvc來測試返回 JSON 內容的 API,并且該 JSON 可能包含一個名為“?shares”的字段作為空數組,或者可能根本不存在(我的意思是“?shares”字段)。JSON 示例:{? ? "id":1234,? ? ?.....? ? "shares":[]}//or{? ? "id":1234,? ? ....}我如何斷言此字段為空或不存在喜歡:mvc.perform(? ? post("....url.......")? ? ? ? .andExpect(status().is(200))? ? ? ? // I need one of the following to be true, but this code will assert both of them, so it will fail? ? ? ? .andExpect(jsonPath("$.shares").isEmpty())? ? ? ? .andExpect(jsonPath("$.shares").doesNotExist())
4 回答
江戶川亂折騰
TA貢獻1851條經驗 獲得超5個贊
這就是您檢查 json 負載中是否不存在該字段的方法。
.andExpect(jsonPath("$.fieldThatShouldNotExist").doesNotExist())如果您希望能夠測試它是否存在且為空或不存在,則必須編寫自己的自定義匹配器來創建類似 XOR 的行為。
楊__羊羊
TA貢獻1943條經驗 獲得超7個贊
使用 MockMVC查看?JsonPath OR 條件
.andExpect(jsonPath("$.isPass",?anyOf(is(false),is(true))));
倚天杖
TA貢獻1828條經驗 獲得超3個贊
如果你有這樣的事情:
{ "arrayFieldName": [] }您可以使用:
.andExpect( jsonPath( "$.arrayFieldName", Matchers.empty() );
那更干凈。
料青山看我應如是
TA貢獻1772條經驗 獲得超8個贊
import static org.hamcrest.collection.IsEmptyCollection.empty;
.andExpect(jsonPath("$.isPass",empty() ));添加回答
舉報
0/150
提交
取消
