[英]How is the "Normalized path expressions" option to Jayway JsonPath used?
[英]default type used by jayway jsonpath?
當我有一個像這樣的價值
x = 0.5771622052130299
我想使用spring 3.2 Resutlmatcher執行以下操作:
.andExpect(jsonPath("$.[1].myX").value(myPojo.getMyX()))
其中myPojo.getMyX返回一個double,測試失敗,因為json轉換為BigDecimal,錯誤是messaeg
java.lang.AssertionError:
For JSON path $.[1].myX type of value expected:
<class java.lang.Double> but was:<class java.math.BigDecimal>
我怎么能避免這個?
我有同樣的問題,但我無法更改Hamcrest用於JSON值(BigDecimal)的類型。
使用此解決方法:
public static final double DEFAULT_PRECISION = 0.000001;
public static Matcher<BigDecimal> closeTo(double value, double precision) {
return BigDecimalCloseTo.closeTo(new BigDecimal(value), new BigDecimal(precision));
}
public static Matcher<BigDecimal> closeTo(double value) {
return closeTo(value, DEFAULT_PRECISION);
}
...
.andExpect(jsonPath("$.values.temperature").value(closeTo(-13.26517)));
我對不同的值有同樣的問題,其中一些被解析為BigDecimal
,一些被解析為double
。
所以我選擇不使用jsonPath,而不是我轉換為使用的實際對象的響應MappingJackson2HttpMessageConverter
:
public class ControllerTest {
@Autowired
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
@SuppressWarnings("unchecked")
protected <T> T toObject(MockHttpServletResponse response, Class<T> clazz) throws IOException{
MockClientHttpResponse inputMessage = new MockClientHttpResponse(response.getContentAsByteArray(),
HttpStatus.valueOf(response.getStatus()));
return (T) mappingJackson2HttpMessageConverter.read(clazz, inputMessage);
}
@Test
public test(){
MvcResult result = mockMvc.perform(get("/rest/url")...)
.andExpect(status().isOk())
.andExpect(content().contentType(APPLICATION_JSON_UTF8))
.andReturn();
MyPojoClass pojo = toObject(result.getResponse(), MyPojoClass.class);
assertArrayEquals(new double[]{0.1, 0.2, 0.3}, pojo.getDoubleArray());
}
}
因為它期待一個大十進制......你可以將雙精度轉換為大十進制
.andExpect(jsonPath("$.[1].myX", is(new BigDecimal(myPojo.getMyX()))))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.