I have a Spring Boot 2.3.2.RELEASE
WebFlux application. I'm building a test for a controller using @WebFluxTest
and injecting a WebTestClient
instance. Everything works fine, but (this one is silly) I can't seem to find a way to retrieve, for a given JSON element/key, its corresponding value (a collection of elements) from the response using JSONPath.
This is the test:
@Test
void getById_Spec() { // HTTP 200 (OK)
final var expected = Entity.reconFoobling();
Mockito.when(service.findById(ArgumentMatchers.any(GetItemsCommand.class)))
.thenReturn(Flux.just(expected));
webClient.get()
.uri(URI_FROM.apply(expected.getId()))
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus().isOk()
.expectHeader().contentType(MediaType.APPLICATION_JSON)
.expectBody()
.jsonPath("$.length()").isEqualTo(1)
.jsonPath("$[0].code").isEqualTo("1001")
...
.jsonPath("$[0].alarms.length()").isEqualTo(2)
.jsonPath("$[0].alarms[0].lanes.length()").isEqualTo(1)
// .jsonPath("$[0].alarms[0].lanes").isEqualTo(List.of("PRIMARY"))
// .jsonPath("$[0].alarms[0].lanes.").isEqualTo(List.of("PRIMARY"))
// .jsonPath("$[0].alarms[0].lanes.*").isEqualTo(List.of("PRIMARY"))
// .jsonPath("$[0].alarms[0].lanes[*]").isEqualTo(List.of("PRIMARY"))
...
.jsonPath("$[0]._id").isEqualTo(1_100L);
Mockito.verifyNoInteractions(gateway, store);
}
No matter what expression I use to get $[0].alarms[0].lanes
(which I test here first: https://jsonpath.com/), it just doesn't work, I'm always getting:
java.lang.AssertionError: JSON path "$[0].alarms[0].lanes" expected:<[PRIMARY]> but was:<null>
Expected :[PRIMARY]
Actual :null
...and I know the JSON I'm receiving is the correct one:
> GET /path/to/1234567890/resources
> WebTestClient-Request-Id: [3]
> Accept: [application/json]
No content
< 200 OK OK
< Content-Type: [application/json]
[{"code":"1001","alarms":[{"lanes":["PRIMARY"]},{"lanes":["SECONDARY"]}],"categories":[],"createdOn":1602268418140,"_id":1100}]