java – 单元测试Spring RESTful控制器时“内容类型未设置”

前端之家收集整理的这篇文章主要介绍了java – 单元测试Spring RESTful控制器时“内容类型未设置”前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我有一个类似于这个的Rest控制器:

@RestController
public class UserRestController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/user/activate",method = RequestMethod.POST)
    public ResponseEntityrequired = true) final String email,@RequestParam(required = true) final String key) {

        UserDTO userDTO = userService.activateAccount(email,key);
        return new ResponseEntity

当我使用Postman调用它并且我不发送’key’参数时,我收到此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: Content type not set

特别是,完成的结果是

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.ResponseEntityrequired String parameter 'email' is not present
             Headers = {}
        Content type = null
                Body = 
       Forwarded URL = null
      Redirected URL = null
             Cookies = []

我推断当抛出异常时,这不会转换为JSON格式(当我发送电子邮件和关键参数时,我得到了正确的JSON结果)

问题很明显:如果抛出异常,我应该在单元测试配置中更改什么来获取JSON错误消息?

最佳答案
问题是在断言失败后测试停止:

.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.

原文链接:https://www.f2er.com/spring/432242.html

猜你在找的Spring相关文章