Spring RestController + Junit测试

Jos*_*chi 8 java junit spring spring-test

我正在玩弹簧框架的弹簧测试.我的目的是在我的休息控制器中测试以下POST方法:

@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;
  }
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试用例:

@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());
    }

}
Run Code Online (Sandbox Code Playgroud)

当我执行它时,我得到状态代码415而不是201.我错过了什么?一个简单的GET请求有效.

raj*_*lli 13

您需要添加注释@EnableWebMvc@RestController工作,这是从你的代码丢失,添加这样便解决了问题