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.
你需要为@RestController
添加注释@EnableWebMvc
才能工作,你的代码中缺少这个,添加这将解决问题
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.