"内容类型未设置"单元测试时Spring RESTful控制器

时间:2015-10-30 13:49:39

标签: java spring rest unit-testing mockmvc

我有一个与此类似的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调用它时,我不会发送&#39;密钥&#39;参数,我收到这条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错误消息?

1 个答案:

答案 0 :(得分:1)

问题是在断言失败后测试停止了:

.andExpect(MockMvcResultMatchers.content().contentType(UtilsUnitTest.APPLICATION_JSON_UTF8))

除此之外,jsonPath("message"...还没有击中任何东西。要验证返回的错误消息,请使用MockMvcResultMatchers.status().reason(<ResultMatcher>)

以下测试应该完成这项工作:

@Test
public void testActivateRequiredParams() throws Exception {
    final ResultActions result = mockMvc
            .perform(MockMvcRequestBuilders.post("/user/activate")
                    .contentType(MediaType.APPLICATION_FORM_URLENCODED).accept(MediaType.APPLICATION_JSON))
            .andDo(MockMvcResultHandlers.print());
    result.andExpect(MockMvcResultMatchers.status().isBadRequest());
    result.andExpect(MockMvcResultMatchers.status().reason(is("Required String parameter 'email' is not present")));
}

但是考虑一下这个(测试错误消息)是不是一个好主意,也许可以看this discussion