I use the Hamcrest CoreMatcher classes as part of the spring-test integration tests. My JSON looks like this:
{"data":[{"distanceInMiles":4,"id":"f97236ba-f4ef-4...
And my integration test is as follows:
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 statement 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 is a separate IsCloseTo : http://hamcrest.org/JavaHamcrest/javadoc/1.3/org/hamcrest/number/IsCloseTo.html , but using it like this:
.andExpect(jsonPath("$.data[0].distanceInMiles", closeTo(miles, 0)))
leads to 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 the need to include some kind of error - I want the return value to be exactly 4 , I just don't care how many zeros are included.
java json spring spring-test hamcrest
Craig otis
source share