gpt4 book ai didi

java - 希望在使用故意错误的 JSON 有效负载时测试预期错误

转载 作者:行者123 更新时间:2023-12-02 08:48:25 25 4
gpt4 key购买 nike

我正在使用 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());

它无法完成测试,因为更新的 Spring 版本在完成请求之前由于 JSON 错误而引发错误(根据下面的错误)。有没有办法让mockMVC在我的测试中预期到错误的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();
}
}

关于java - 希望在使用故意错误的 JSON 有效负载时测试预期错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60937987/

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