我正在使用Junit和MockMVC进行一些集成测试...我们的测试之一按预期工作,直到我们刚刚升级到Spring Boot 2.2.5。
mockMvc.perform(
post("/experiments")
.contentType(MediaType.APPLICATION_JSON)
.content(requestPayload)) // requestPayload is a purposefully invalid JSON string with a missing bracket
.andDo(print())
.andExpect(status().isBadRequest());
它无法完成测试,因为由于错误的JSON,更新的Spring版本在完成请求之前会引发错误(请参见以下错误)。有没有一种方法可以使嘲笑MVC在我的测试中出现错误的JSON?
Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: JSON conversion problem: Unexpected character ('{' (code 123)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
at [Source: (PushbackInputStream); line: 1, column: 232] (through reference chain: com.allstate.d3.sh.commons.rest.ExperimentDetail["buckets"]->java.util.ArrayList[0])
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.http.converter.HttpMessageConversionException: JSON conversion problem: Unexpected character ('{' (code 123)): was expecting double-quote to start field name; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Unexpected character ('{' (code 123)): was expecting double-quote to start field name
at [Source: (PushbackInputStream); line: 1, column: 232] (through reference chain: com.allstate.d3.sh.commons.rest.ExperimentDetail["buckets"]->java.util.ArrayList[0])
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
我认为该异常不是在MockMvc
中引发,而是在您的应用程序中引发。您可以注册一个RestControllerAdvice
来处理它并产生您期望的错误请求响应:
@RestControllerAdvice
public class ErrorController {
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageConversionException.class)
public String handleBadRequest(Exception e) {
return e.getMessage();
}
}