Spring测试中如何用JsonPath和Hamcrest断言JSON属性大于0?
问题:Spring MockMvc验证JSON中stockValue大于0失败
我得到的JSON响应如下:
{ "stockId": 1, "stockName": "SPOT", "stockValue": 150.00 }
我需要验证stockValue大于0,尝试了两种写法均出现编译错误:
第一种写法及错误
代码:
.andExpect(jsonPath("$.stockValue"), Matchers.greaterThan(0.00));
编译错误:
'andExpect(org.springframework.test.web.servlet.ResultMatcher)' in 'org.springframework.test.web.servlet.ResultActions' cannot be applied to '(org.springframework.test.web.servlet.result.JsonPathResultMatchers, org.hamcrest.Matcher<java.lang.Double>)'
第二种写法及错误
代码:
.andExpect(jsonPath("$.stockValue"), Matchers.everyItem(Matchers.greaterThan(0.00)));
编译错误:
'andExpect(org.springframework.test.web.servlet.ResultMatcher)' in 'org.springframework.test.web.servlet.ResultActions' cannot be applied to '(org.springframework.test.web.servlet.result.JsonPathResultMatchers, org.hamcrest.Matcher<java.lang.Iterable<? extends java.lang.Double>>)'
我的完整测试函数:
@Test void getStockDetail200() throws Exception { // Perform the GET request String endpoint = MessageFormat.format("{0}?symbol=SPOT&{1}", Utils.BASE_URL, Utils.TOKEN); mockMvc.perform(get(endpoint) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.stockName", Matchers.is("SPOT"))) .andExpect(jsonPath("$.stockValue"), Matchers.greaterThan(0.00)); }
解决方案
问题根源
你错误地将jsonPath返回的JsonPathResultMatchers对象和Matcher作为两个参数传给了andExpect,但andExpect只接受一个ResultMatcher类型的参数。此外,everyItem是用于验证集合元素的匹配器,而stockValue是单个数值,完全不需要使用它。
正确写法
将Matcher作为jsonPath方法的第二个参数传入,这样jsonPath会直接返回符合要求的ResultMatcher:
.andExpect(jsonPath("$.stockValue", Matchers.greaterThan(0.00)));
如果导入了以下静态方法:
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*; import static org.hamcrest.Matchers.*;
代码可以进一步简化为:
.andExpect(jsonPath("$.stockValue", greaterThan(0.00)));
修正后的完整测试代码
@Test void getStockDetail200() throws Exception { String endpoint = MessageFormat.format("{0}?symbol=SPOT&{1}", Utils.BASE_URL, Utils.TOKEN); mockMvc.perform(get(endpoint) .contentType(MediaType.APPLICATION_JSON)) .andExpect(status().isOk()) .andExpect(jsonPath("$.stockName", is("SPOT"))) .andExpect(jsonPath("$.stockValue", greaterThan(0.00))); }
内容的提问来源于stack exchange,提问作者meniman98
相关产品推荐
相关产品推荐

