I'm using the Hamcrest CoreMatcher
classes as part of spring-test
integration tests. My JSON looks like:
{"data":[{"distanceInMiles":4,"id":"f97236ba-f4ef-4...
And my integration test looks like:
double miles = 4.0
Activity a = new BasicActivity(miles);
this.activityManager.add(a); // A mock activity manager (in-memory)
...
this.mockMvc.perform(get("/").accept("application/json"))
.andExpect(jsonPath("$.data[0].distanceInMiles", is(miles)))
However, the assertion fails:
java.lang.AssertionError: JSON path "$.data[0].distanceInMiles"
Expected: is <4.0>
but: was <4>
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
I know that there's a separate IsCloseTo
matcher here: http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/number/IsCloseTo.html, but using it like so:
.andExpect(jsonPath("$.data[0].distanceInMiles", closeTo(miles, 0)))
results in a strange error:
java.lang.AssertionError: JSON path "$.data[0].distanceInMiles"
Expected: a numeric value within <0.0> of <4.0>
but: was a java.lang.Integer (<4>)
at org.hamcrest.MatcherAssert.assertThat(MatcherAssert.java:20)
I was hoping to avoid having to include some kind of error - I want the returned value to be exactly 4
, I just don't care how many trailing zeroes are included.
double
value is used to create the model object that is then checked for as part of the JSON response, so I was hoping to reuse the same variable to avoid typing it twice. I'll update my codeblock to demonstrate. – Vainglorious