You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 01:34:50