mardi 5 décembre 2017

Why am I getting HttpMediaTypeNotSupportedException?

I have the following Spring controller:

@Api(name = "Some API", description = "Description")
@RestController
@RequestMapping("/api/mystuff")
public class SomeController {

    @RequestMapping(value = "/create", method = RequestMethod.POST,
            consumes = MediaType.APPLICATION_JSON_VALUE)
    public PartnerAccount create(HttpServletRequest request, @RequestBody PartnerAccount account) throws UserAuthorizationException {
    [...]    
    }
}

Then I try to test this method:

public void create() throws Exception {
    final String token = getAccessTokenForAdmin();
    final PartnerAccount account = createPartnerAccount();
    final byte[] reqBytes = TestUtil.convertObjectToJsonBytes(account);
    final String reqString = new String(reqBytes);
    MvcResult mvcResult = getMockMvc()
            .perform(
                    post("/api/mystuff/create")
                            .contentType(MediaType.APPLICATION_JSON)
                            .content(reqBytes)
                            .header(TestUtil.AUTHORIZATION,
                                    TestUtil.BEARER + token)
            ).andReturn();
}

TestUtil.convertObjectToJsonBytes(account) is defined as follows.

public static byte[] convertObjectToJsonBytes(Object object) throws IOException {
    ObjectMapper mapper = new ObjectMapper();
    mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
    return mapper.writeValueAsBytes(object);
}

When I execute this test, the method org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodArgumentResolver#readWithMessageConverters(org.springframework.http.HttpInputMessage, org.springframework.core.MethodParameter, java.lang.reflect.Type) throws the exception

throw new HttpMediaTypeNotSupportedException(contentType, this.allSupportedMediaTypes);

at the location indicated by the comment // The exception is thrown here on line 79 in this gist while processing the POST request. Here are the values of contentType and this.allSupportedMediaTypes:

Values of variables

application/json seems to be among the supported media types, but the exception is thrown nonetheless.

How can I fix it?

What I have tried so far (and it didn't help)

  • Adding @EnableWebMvc as suggested here. This annotation was already present in the applicable test configuration.
  • Remove excludeFilters` as suggested here - I don't have any @ExcludeFilters annotations in the code.

Aucun commentaire:

Enregistrer un commentaire