toedter / spring-hateoas-jsonapi

A JSON:API media type implementation for Spring HATEOAS
Apache License 2.0
106 stars 15 forks source link

Top level data and relationships key not in MVC Web test result #66

Closed RabeeHanna closed 1 year ago

RabeeHanna commented 1 year ago

Hi, I am trying to add a test to confirm the correct keys are returned from my controller, this test is similar to the ones found in this repo. My controller maps a GET to /api/events/ to a method with return type ResponseEntity<RepresentationModel<?>>, which is generated using the JsonApiModelBuilder.

mockMvc.perform(get("/api/events/" + eventDto.getUuid()).accept("application/vnd.api+json"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.id", is(eventDto.getUuid())))
                .andExpect(jsonPath("$.data.type", is("events")))
                .andExpect(jsonPath("$.links.self", is("http://localhost/api/events/" + eventDto.getUuid())));

The result shows that the data key is missing, but I can confirm that it is there when running my code outside of tests. It looks like the Body from MockHttpServletResponse does not include "data" there either, or the relationships either...

MockHttpServletResponse:
           Status = 200
    Error message = null
          Headers = [Content-Type:"application/vnd.api+json"]
     Content type = application/vnd.api+json
             Body = {"uuid":"df46fc82-6874-4ddd-b582-81c695f38ed7", ... (remaining attributes) ..., "links":[],"links":[{"rel":"self","href":"http://localhost/api/events/df46fc82-6874-4ddd-b582-81c695f38ed7"}]}
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

No value at JSON path "$.data.id"
java.lang.AssertionError: No value at JSON path "$.data.id"
...

I'm not sure why the response for this test has just the attributes and links and not the entire JSON:API object. Just wondering if anyone has seen this issue while testing. Thanks!

toedter commented 1 year ago

Hello Rabee, thanks for reporting this.

It should work, as you would expect. From your description I would guess that somehow the JSON:API serializer is not used in your test at all. You find many working examples here: https://github.com/toedter/spring-hateoas-jsonapi-examples. Take a look at the example-basic sub project, probably you figure out what the difference to your setup is.

If it would help you could zip a running example with the bahaviour you described to kai@toedter.com, then I could take a look at it.

RabeeHanna commented 1 year ago

Thank you, turns out it was because I didn't have the @SpringBootTest annotation. I left it out and tried using just @WebMvcTest(Controller.class) instead to speed up my tests, but it seems there are requirements that WebMvcTest does not add completely. The slowness can't be avoided for these kind of integration tests I assume