使用Spring MockMVC时,如何为结果添加OR断言条件?
实现MockMvc JSON断言的OR条件
你需要借助Hamcrest的anyOf()匹配器来实现逻辑或断言,该匹配器支持传入多个子匹配器,只要其中一个匹配成功,整个断言就会通过。
修改后的可行代码如下:
.andExpect(org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath("$.message", org.hamcrest.Matchers.anyOf( org.hamcrest.Matchers.equalTo("storeCode cannot be blank text; storeCode cannot be null"), org.hamcrest.Matchers.equalTo("storeCode cannot be null; storeCode cannot be blank text") ) ));
补充说明
如果提前导入静态包,代码可以进一步简化:
// 先添加静态导入 import static org.hamcrest.Matchers.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; // 简化后的断言代码 .andExpect(jsonPath("$.message", anyOf( equalTo("storeCode cannot be blank text; storeCode cannot be null"), equalTo("storeCode cannot be null; storeCode cannot be blank text") ) ));
内容的提问来源于stack exchange,提问作者CodeBot
相关产品推荐
相关产品推荐

