gpt4 book ai didi

java - "Content type not set"单元测试 Spring RESTful Controller 时

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:31:59 43 4
gpt4 key购买 nike

我有一个类似于这个的 Rest Controller :

@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 调用它并且没有发送“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 消息。事实上,我得到一个异常(exception):

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.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 错误消息?

最佳答案

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

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

关于java - "Content type not set"单元测试 Spring RESTful Controller 时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33437603/

43 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com