Spring RestController + Junit Testing

纵饮孤独 提交于 2020-01-02 02:52:25

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/37458037/spring-restcontroller-junit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!