我将JUnit4与Spring Web MVC Test结合使用,并且具有Controller的测试类。
控制器处理POST请求以使用JSON正文内容“ /测试”。我已经使用Postman手动测试了此方法,并且由于预期的“ name”属性为空,因此收到了400错误的请求响应,正如预期的那样。
POST /Server/test HTTP/1.1
Host: localhost:8080
Content-Type: application/json
Cache-Control: no-cache
{
"name": ""
}
但是,当我通过测试类向控制器发送相同的请求时,即使请求相同,也会收到415(不支持的媒体类型)错误。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class MyControllerTest {
@Configuration
public static class MyControllerTestConfiguration {
@Bean
public MyController myController() {
return new MyController();
}
}
private MockMvc mockMvc;
@Before
public void setup() {
mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void shouldReturnBadRequest_IfBodyIsEmpty() throws Exception {
// Works fine
mockMvc.perform(post("/test"))
.andExpect(status().isBadRequest());
}
@Test
public void shouldReturnBadRequest_IfInvalidFields() throws Exception {
MyDTO dto = new MyDTO();
dto.setName("");
// Jackson object mapper
ObjectMapper mapper = new ObjectMapper();
// TEST FAIL: Gets 415 error
mockMvc.perform(
post("/test")
.content(mapper.writeValueAsString(dto))
.characterEncoding("UTF-8")
.contentType(MediaType.APPLICATION_JSON)
)
.andDo(print())
.andExpect(status().isBadRequest());
}
}
这是MyController。
@RestController
@EnableWebMvc
public class MyController {
@RequestMapping(value = "/test", method = RequestMethod.POST)
public void init(@javax.validation.Valid @RequestBody MyDTO dto) {
}
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public void validationError(MethodArgumentNotValidException ex) {
}
}
这是MyDTO。
@lombok.Data
public class MyDTO {
private String name;
}
我的依赖项中也有Jackson。
这是将测试类的请求打印到控制台后的样子:
MockHttpServletRequest:
HTTP Method = POST
Request URI = /test
Parameters = {}
Headers = {Content-Type=[application/json;charset=UTF-8]}
Body = {"name":""}
Session Attrs = {}
Handler:
Type = controller.MyController
Method = public void controller.MyController.init(dto.MyDTO)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.HttpMediaTypeNotSupportedException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
Attributes = null
MockHttpServletResponse:
Status = 415
Error message = null
Headers = {Accept=[application/octet-stream, text/plain, application/xml, text/xml, application/x-www-form-urlencoded, application/*+xml, multipart/form-data, */*]}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
无论如何,为什么我会得到这个错误?该请求对我来说似乎很好。任何帮助表示赞赏。谢谢。
最佳答案
我已经通过使用@EnableWebMvc注释MyControllerTestConfiguration内部静态类解决了该问题。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
@WebAppConfiguration
public class MyControllerTest {
@Configuration
@EnableWebMvc // <------------ added this
public static class MyControllerTestConfiguration {
@Bean
public SetupController setupController() {
return new MyController();
}
}