当使用有目的的不良JSON有效负载时,要测试预期的错误

问题描述 投票:0回答:1

我正在使用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)
java spring junit mockmvc
1个回答
1
投票

我认为该异常不是在MockMvc中引发,而是在您的应用程序中引发。您可以注册一个RestControllerAdvice来处理它并产生您期望的错误请求响应:

@RestControllerAdvice
public class ErrorController {

    @ResponseStatus(HttpStatus.BAD_REQUEST)
    @ExceptionHandler(HttpMessageConversionException.class)
    public String handleBadRequest(Exception e) {
        return e.getMessage();
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.