我有一个与此类似的 Rest 控制器:
@RestController
public class UserRestController {
@Autowired
private UserService userService;
@RequestMapping(value = "/user/activate", method = RequestMethod.POST)
public ResponseEntity<UserDTO> activate(
@RequestParam(required = true) final String email,
@RequestParam(required = true) final String key) {
UserDTO userDTO = userService.activateAccount(email, key);
return new ResponseEntity<UserDTO>(userDTO, HttpStatus.OK);
}
}
当我使用 Postman 调用它并且不发送“密钥”参数时,我会收到以下 JSON 消息:
{
"timestamp": 1446211575193,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.web.bind.MissingServletRequestParameterException",
"message": "Required String parameter 'key' is not present",
"path": "/user/activate"
}
另一方面,我正在使用 JUnit 和 MockMVC Spring 实用程序测试此方法。
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = ApplicationConfig.class)
@WebAppConfiguration
public class UserRestControllerTest {
private static MockMvc mockMvc;
@Mock
private UserService userService;
@InjectMocks
private UserRestController userRestController;
@Before
public void setup() {
MockitoAnnotations.initMocks(this);
mockMvc = MockMvcBuilders
.standaloneSetup(userRestController)
.setMessageConverters(
new MappingJackson2HttpMessageConverter(),
new Jaxb2RootElementHttpMessageConverter()).build();
}
@Test
public void testActivateRequiredParams() throws Exception {
mockMvc.perform(
MockMvcRequestBuilders.post("/user/activate")
.contentType(MediaType.APPLICATION_FORM_URLENCODED)
.accept(MediaType.APPLICATION_JSON))
.andDo(MockMvcResultHandlers.print())
.andExpect(MockMvcResultMatchers.status().isBadRequest())
.andExpect(
MockMvcResultMatchers.content().contentType(
UtilsUnitTest.APPLICATION_JSON_UTF8))
.andExpect(
jsonPath(
"message",
is("Required String parameter 'email' is not present")));
}
}
但是当我执行这个测试时,我注意到响应不是 JSON 消息。事实上,我得到了一个例外:
java.lang.AssertionError:未设置内容类型
特别是,完成的结果是
MockHttpServletRequest:
HTTP Method = POST
Request URI = /user/activate
Parameters = {}
Headers = {Content-Type=[application/x-www-form-urlencoded]}
Handler:
Type = com.company.controller.UserRestController
Method = public org.springframework.http.ResponseEntity<com.company.dto.UserDTO> com.company.controller.UserRestController.activate(java.lang.String,java.lang.String)
Async:
Async started = false
Async result = null
Resolved Exception:
Type = org.springframework.web.bind.MissingServletRequestParameterException
ModelAndView:
View name = null
View = null
Model = null
FlashMap:
MockHttpServletResponse:
Status = 400
Error message = Required String parameter 'email' is not present
Headers = {}
Content type = null
Body =
Forwarded URL = null
Redirected URL = null
Cookies = []
我推断当抛出异常时,它不会转换为 JSON 格式(我在发送电子邮件和关键参数时得到正确的 JSON 结果)
问题很明显:如果抛出异常,我应该在单元测试配置中更改什么以获得 JSON 错误消息?