Spring RestController + Junit 测试
Spring RestController + Junit Testing
我正在玩 spring-测试 spring 框架。我的目的是在我的休息控制器中测试以下 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;
}
}
这是我的测试用例:
@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());
}
}
当我执行它时,我得到状态代码 415 而不是 201。我错过了什么?一个简单的 GET 请求就可以了。
您需要添加注释 @EnableWebMvc
才能使 @RestController
正常工作,您的代码中缺少此注释,添加此注释将解决问题
我正在玩 spring-测试 spring 框架。我的目的是在我的休息控制器中测试以下 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;
}
}
这是我的测试用例:
@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());
}
}
当我执行它时,我得到状态代码 415 而不是 201。我错过了什么?一个简单的 GET 请求就可以了。
您需要添加注释 @EnableWebMvc
才能使 @RestController
正常工作,您的代码中缺少此注释,添加此注释将解决问题