5

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 ?

NimChimpsky
  • 46,453
  • 60
  • 198
  • 311

4 Answers4

0

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

Code from an unrelated question may also help.

References

Community
  • 1
  • 1
Paul Sweatte
  • 24,148
  • 7
  • 127
  • 265
0

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)));
Niels
  • 1
0

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

}
lotusdragon
  • 486
  • 4
  • 6
0

Since it is expecting a Big Decimal...you can convert the double to Big Decimal

.andExpect(jsonPath("$.[1].myX", is(new BigDecimal(myPojo.getMyX()))))
Ajay Reddy
  • 1,475
  • 1
  • 16
  • 20