0

I'm trying to check in my integration test if all of values from some specific property has the same type. I was trying to do it along with jsonPath and JsonPathResultMatchers but without success. Finally in I did something like this :

MvcResult result = mockMvc.perform(get("/weather/" + existingCity))
                 .andExpect(MockMvcResultMatchers.status().isOk())
                 .andReturn();


String responseContent = result.getResponse().getContentAsString();
TypeRef<List<Object>> typeRef = new TypeRef<List<Object>>() {
};

List<Object> humidities = JsonPath.using(configuration).parse(responseContent).read("$.*.humidity", typeRef);
Assertions.assertThat(humidities.stream().allMatch(humidity -> humidity instanceof Integer)).isTrue();

But I wonder if exist some clearer way to do this, can the same result be achieved with JSONPath ? Or AssertJ has some method to find it without usage stream code

Artur Skrzydło
  • 1,135
  • 18
  • 37

2 Answers2

4

Just answering on the AssertJ part: Stream assertions are provided with some caveats as the Stream under test is converted to a List in order to be able to perform multiple assertions (otherwise you can't as a Stream can only be consumed once).

Javadoc: assertThat(BaseStream)

Example:

assertThat(DoubleStream.of(1, 2, 3)).isNotNull()
                                    .contains(1.0, 2.0, 3.0)
                                    .allMatch(Double::isFinite);

I have happily used https://github.com/lukas-krecan/JsonUnit to check JSON, you can give it a try and see if you like it.

Joel Costigliola
  • 6,308
  • 27
  • 35
1

I personnaly would rather validate it against a JSON schema. There are Java validator implementations that could help you

C.Champagne
  • 5,381
  • 2
  • 23
  • 35