0

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}]
x80486
  • 6,627
  • 5
  • 52
  • 111
  • It looks like your input JSON is invalid; or is the missing `}` just a typo? `["SECONDARY"]}]` – wp78de Oct 12 '20 at 15:17
  • It is/was a typo; I try not to share many details because it's from work (and they are "special" folks), so I edit the field details, etc.; but it's definitely valid JSON, you can overrule that ;) – x80486 Oct 13 '20 at 13:08
  • It is not-great to have your JSON be a giant single-element list. Can you remove the outer brackets? – MarkHu May 16 '21 at 03:59

0 Answers0