1
votes

Hopefully someone can help. I've been following this online resource, attempting to write an integration test for a RestController:

@Test
public void obfiscated() throws Exception {
    SearchRequest autoCompleteSearchrequest = new SearchRequest();
    autoCompleteSearchrequest.setCity("somewheresville");
    autoCompleteSearchrequest.setSuggestionsField(Constants.FIELDNAME_POSTCODE);
    mockMvc.perform(MockMvcRequestBuilders
            .post(PATH_TO_AUTOCOMPLETE_SERVICE_V2)
            .content(asJsonString(autoCompleteSearchrequest))
            .contentType(MediaType.APPLICATION_JSON)
            .accept(MediaType.APPLICATION_JSON))
            .andExpect(status().isCreated());

}

public static String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Controller under test:

@JsonProperty
@PreAuthorize(HAS_AUTHORITY_USER_OR_ADMIN)
@RequestMapping( value = PATH_TO_AUTOCOMPLETE_SERVICE_V2, method = RequestMethod.POST)
public ResponseEntity<String> obfiscated(@RequestBody SearchRequest autoCompleteSearchrequest) {

ObfiscatedeResponse response = this.searchService.obfiscated(obfiscatedrequest);
    String response = new Gson().toJson(response);
    return new ResponseEntity<String>(response, HttpStatus.OK);
}

Can anyone see why I get this response:

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/wandb/autocompletev2
       Parameters = {}
          Headers = [Content-Type:"application/octet-stream", Content-Length:"127"]
             Body = <no character encoding set>
    Session Attrs = {SPRING_SECURITY_CONTEXT=org.springframework.security.core.context.SecurityContextImpl@c952e25: Authentication: org.springframework.security.authentication.UsernamePasswordAuthenticationToken@c952e25: Principal: org.springframework.security.core.userdetails.User@1968e: Username: ich; Password: [PROTECTED]; Enabled: true; AccountNonExpired: true; credentialsNonExpired: true; AccountNonLocked: true; Granted Authorities: ROLE_USER; Credentials: [PROTECTED]; Authenticated: true; Details: null; Granted Authorities: ROLE_USER}

Handler:
             Type = com.obfiscated.SearchController
           Method = com.obfiscated.SearchController#autocomplete(SearchRequest)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotSupportedException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 415
    Error message = null
          Headers = [Accept:"application/octet-stream, text/plain, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, multipart/mixed, */*"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []
[2021-04-12 13:59:14,772] [WARN ] X=[] U=[] [o.s.w.s.m.s.DefaultHandlerExceptionResolver] [Resolved [org.springframework.web.HttpMediaTypeNotSupportedException: Content type 'application/json' not supported]]

MockHttpServletRequest:
      HTTP Method = POST
      Request URI = /api/wandb/autocompletev2
       Parameters = {}
          Headers = [Content-Type:"application/json", Accept:"application/json", Content-Length:"127"]
             Body = <no character encoding set>
    Session Attrs = {}

Handler:
             Type = com.obfiscated.Controller
           Method = com.obfiscated.Controller#obfiscated(SearchRequest)

Async:
    Async started = false
     Async result = null

Resolved Exception:
             Type = org.springframework.web.HttpMediaTypeNotSupportedException

ModelAndView:
        View name = null
             View = null
            Model = null

FlashMap:
       Attributes = null

MockHttpServletResponse:
           Status = 415
    Error message = null
          Headers = [Accept:"application/octet-stream, text/plain, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, multipart/mixed, */*"]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

Edit:

MockHttpServletRequest: HTTP Method = POST Request URI = /api/wandb/autocompletev2 Parameters = {} Headers = [Content-Type:"application/json", Accept:"application/json", Content-Length:"127"] Body = Session Attrs = {}

Handler: Type = com.obfiscated.SearchController Method = com.obfiscated.SearchController#autocomplete(SearchRequest)

Async: Async started = false Async result = null

Resolved Exception: Type = org.springframework.web.HttpMediaTypeNotSupportedException

ModelAndView: View name = null View = null Model = null

FlashMap: Attributes = null

MockHttpServletResponse: Status = 415 Error message = null Headers = [Accept:"application/octet-stream, text/plain, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, multipart/mixed, /"] Content type = null Body = Forwarded URL = null Redirected URL = null Cookies = []

The above response was when I added , consumes = MediaType.APPLICATION_JSON_VALUE to the RequestMapping.

2
What is @JsonProperty meant to define here? I'm not sure it even makes sense on a controller. Did you want to define the controller returns Json? You probably want to look at the consumes and produces attributes of @RequestMapping(). - Thomas
quite right @Thomas. renoved. - HellishHeat
Have you setup the accept headers through some configuration or through filters? Your mock servlet response returning accept headers which doesn't contain application/json. - code_mechanic

2 Answers

2
votes

Despite my, admittedly false, belief that this is taken care of by the @SpringBootTest annotation; I took advice found in another question, and added @EnableWebMvc at class level for my test, and that fixed it.

0
votes

try adding consumes = MediaType.APPLICATION_JSON_VALUE to your RequestMapping