Java Spring RestController + Junit 测试
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37458037/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring RestController + Junit Testing
提问by Joschi
I'm playing around with spring-test of springframework. My intention is to test the following POST method in my rest controller:
我正在玩 spring 框架的弹簧测试。我的目的是在我的 rest 控制器中测试以下 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;
}
}
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.
当我执行它时,我得到状态代码 415 而不是 201。我错过了什么?一个简单的 GET 请求有效。
采纳答案by rajadilipkolli
You need to add annotation @EnableWebMvc
for @RestController
to work, this is missing from your code, adding this will solve the issue
您需要添加注释@EnableWebMvc
的@RestController
工作,这是从你的代码丢失,添加这样便解决了问题