简体   繁体   中英

default type used by jayway jsonpath?

when I have a value such as

x = 0.5771622052130299

and I want to do the following, using spring 3.2 Resutlmatcher :

.andExpect(jsonPath("$.[1].myX").value(myPojo.getMyX()))

where myPojo.getMyX returns a double, the test fails as the json is converted to a BigDecimal, with the error messaeg

java.lang.AssertionError: 
For JSON path $.[1].myX type of value expected:
<class java.lang.Double> but was:<class java.math.BigDecimal>

How can I avoid this ?

Use Hamcrest to create a custom matcher which casts to BigDecimal. Here is a tutorial:

Code from an unrelated question may also help.

References

I had the same problem but I could not change the type Hamcrest was using for the JSON value (BigDecimal).

Used this Workaround:

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)));

I had the same problem with different values where some were parsed as BigDecimal and some as double .

So I choose not to use jsonPath, instead I convert the response to the actual object using 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()))))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM