Spring MVC testing results in 415 error

I ran into this issue and was able to fix it by adding the @EnableWebMvc annotation to my test's SpringContext class.


Hello change your controller's method params consumes and produces to:

consumes = MediaType.APPLICATION_JSON_VALUE,produces = MediaType.APPLICATION_JSON_VALUE

and your test case to

@Test
    public void testAddProject() throws Exception {
        ProjectInput input = new ProjectInput("name", "description");
        mockMvc.perform(post("/projects/")
                .contentType(MediaType.APPLICATION_JSON)
                .content(new ObjectMapper().writeValueAsString(input)))
            .andExpect(status().isOk())
            .andExpect(content().contentType(MediaType.APPLICATION_JSON));
    }

EDIT:

The problem is in your Project class. Missing default constructor.


I had a similar case and I could solve it by adding both header-accept AND content-type.

Headers = {Accept=[application/json;charset=UTF-8], 
                   Content-Type=[application/json;charset=UTF-8]}

In the test module:

MediaType MEDIA_TYPE_JSON_UTF8 = new MediaType("application", "json", java.nio.charset.Charset.forName("UTF-8"));
MockHttpServletRequestBuilder request = post("/myPostPath");
request.content(json);
request.locale(Locale.JAPANESE);
request.accept(MEDIA_TYPE_JSON_UTF8);
request.contentType(MEDIA_TYPE_JSON_UTF8);
mockMvc.perform(request)
    .andDo(print())
    .andExpect(status().isOk());

First I only put request.accept(..). But after adding request.contentType(..) it finally worked.