9

I'm playing around with spring-test of springframework. My intention is to test the following POST method in my rest controller:

@RestController
@RequestMapping("/project")
public class ProjectController {

  @RequestMapping(method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
  public Project createProject(@RequestBody Project project, HttpServletResponse response) {
    // TODO: create the object, store it in db...
    response.setStatus(HttpServletResponse.SC_CREATED);
    // return the created object - simulate by returning the request.
    return project;
  }
}

This is my test case:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {ProjectController.class })
@WebAppConfiguration
public class ProjectControllerTest {

    private MockMvc mockMvc;

    @Autowired
    private WebApplicationContext wac;

    @Before
    public void setUp() {
        mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
    }

    @Test
    public void testCreationOfANewProjectSucceeds() throws Exception {
        Project project = new Project();
        project.setName("MyName");
        String json = new Gson().toJson(project);

        mockMvc.perform(
                post("/project")
                        .accept(MediaType.APPLICATION_JSON)
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(json))
                .andExpect(status().isCreated());
    }

}

When I execute it I get Status Code 415 instead of 201. What am I missing? A simple GET request works.

Joschi
  • 2,118
  • 3
  • 16
  • 32
  • 1
    Do you have Jackson or another JSON library (if message converter based on some other) available in classpath so Spring's message converter can convert it? – Stan May 26 '16 at 11:09
  • I have Gson available. I'll test it with Jackson again. Just saw that when @RequestBody is a String it works so it appears that the conversion won't work – Joschi May 26 '16 at 11:12
  • The annotation @EnableWebMvc was missing on my controller. Now it works. Thanks for the reply! – Joschi May 26 '16 at 11:17

1 Answers1

14

You need to add annotation @EnableWebMvc for @RestController to work, this is missing from your code, adding this will solve the issue

rajadilipkolli
  • 3,475
  • 2
  • 26
  • 49