Spring Boot 测试自定义错误控制器

     2023-02-27     133

关键词:

【中文标题】Spring Boot 测试自定义错误控制器【英文标题】:SpringBoot test custom Errors Controller 【发布时间】:2017-12-03 18:43:15 【问题描述】:

按照此处Spring Boot Remove Whitelabel Error Page 的建议,我创建了一个自定义错误控制器,以 json 格式返回自定义错误响应,如下所示

@RestController
public class CustomErrorController implements ErrorController 

private static final String PATH = "/error";

@Value("$spring.debug:false")
private boolean debug;

@Autowired
private ErrorAttributes errorAttributes;

  @RequestMapping(value = PATH)
  ErrorJson error(HttpServletRequest request, HttpServletResponse response) 
    return new ErrorJson(response.getStatus(), getErrorAttributes(request, debug));
  

  private Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) 
    RequestAttributes requestAttributes = new ServletRequestAttributes(request);
    return errorAttributes.getErrorAttributes(requestAttributes, includeStackTrace);
  

  @Override
  public String getErrorPath() 
    return PATH;
  


其中CustomErrorController 实现ErrorControllerErrorJson 只是一个用于格式化json 错误响应的简单类。

现在我正在尝试编写一个测试,以测试是否命中了一个不存在的端点,CustomErrorController 会处理它并返回一个带有 json 响应的 404,例如:


  "status": 404,
  "error": "Not Found",
  "message": "No message available",
  "timeStamp": "Thu Jun 29 14:55:44 PDT 2017",
  "trace": null

我的测试目前看起来像

@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class CustomErrorControllerTest 

    @Autowired
    private MockMvc mockMvc;


    @Test
    public void invalidURLGet() throws Exception 
        mockMvc.perform(MockMvcRequestBuilders.get("/foo"))
                .andExpect(status().is(404))
                .andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8))
                .andReturn();

    



我收到状态为404 的错误响应,但内容主体为空,MockHttpServletResponse 为:

MockHttpServletResponse:
           Status = 404
    Error message = null
          Headers = X-Application-Context=[application:development:-1]
     Content type = null
             Body = 
    Forwarded URL = null
   Redirected URL = null
          Cookies = []

所以,我有两个问题:

    为什么内容主体为空。 MockMvc 是否找不到 CustomErrorController。 我是否错误地测试了错误行为。如果是这样,我该如何测试自定义错误响应?

【问题讨论】:

【参考方案1】:

您可以使用TestRestTemplate 来获得更多信息。这不仅可以让您进行适当的 URI 调用,还可以让您有机会将您的响应序列化为它返回的实际对象,以验证您的主体和其他元素是否确实存在。

简单示例:

// Elsewhere...
@Autowired
private TestRestTemplate template;

// In your tests...
ErrorJson result = template.getForObject("/error", ErrorJson.class);

// Inspect the result!

【讨论】:

尝试使用TestRestTemplate,但现在出现以下错误。 ****************************** 应用程序无法启动 ******************* ******** 描述:配置为侦听端口 0 的 Tomcat 连接器启动失败。该端口可能已在使用中,或者连接器可能配置错误。行动:验证连接器的配置,识别并停止正在侦听端口 0 的任何进程,或将此应用程序配置为侦听另一个端口。 那么...您确定为您的测试设置了一个随机端口?我给你的链接中提供了如何做到这一点。 是的,使用@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)

测试开发专题:spring-boot自定义返回参数校验错误信息

之前两篇文章Spring-boot自定义参数校验注解和如何在spring-boot中进行参数校验,我们介绍了,参数校验以及如何自定义参数校验注解,但是当传递参数出错时,只是把错误信息打印到了控制台,合理的做法是应该把校验的错误信... 查看详情

使用自定义 ErrorAttributes 测试 Spring Boot 应用程序?

】使用自定义ErrorAttributes测试SpringBoot应用程序?【英文标题】:TestingaSpringBootapplicationwithcustomErrorAttributes?【发布时间】:2015-05-2104:07:23【问题描述】:我正在尝试测试应使用自定义错误属性的SpringBootRestController。@BeanpublicErrorAtt... 查看详情

使用自定义 ErrorAttributes 测试 Spring Boot 应用程序?

】使用自定义ErrorAttributes测试SpringBoot应用程序?【英文标题】:TestingaSpringBootapplicationwithcustomErrorAttributes?【发布时间】:2015-05-2104:07:23【问题描述】:我正在尝试测试应使用自定义错误属性的SpringBootRestController。@BeanpublicErrorAtt... 查看详情

Spring Boot Thymeleaf 自定义验证器不显示错误

...有问题,它没有显示自定义注释验证器捕获的验证错误。控制器:@RequestMapping(value="/register",method=RequestMethod.POS 查看详情

spring boot中自定义验证的参数化junit测试

】springboot中自定义验证的参数化junit测试【英文标题】:Parameterizedjunittestofcustomvalidationinspringboot【发布时间】:2021-09-0507:00:58【问题描述】:我在springboot中有这个验证器,当整数不在1和3之间时会给出错误,并且我正在使用addCo... 查看详情

在 Spring Boot MVC 测试中自定义 bean

】在SpringBootMVC测试中自定义bean【英文标题】:customizebeansinspringbootMVCtest【发布时间】:2017-06-2101:34:51【问题描述】:我正在使用Spring-boot1.4.0.RELEASE。已按照建议构建了一个MVCint测试https://docs.spring.io/spring-boot/docs/current/reference/htm... 查看详情

使用邮递员返回错误请求,但未在单元测试 Spring Boot 中返回

...果很好。我正在尝试在我的SpringBoot应用程序上测试我的控制器,如果数据重复(唯一名称) 查看详情

Spring Boot:自定义属性配置和测试

】SpringBoot:自定义属性配置和测试【英文标题】:SpringBoot:custompropertiesconfigurationandtests【发布时间】:2018-11-1400:49:27【问题描述】:我正在使用带有默认application.yml属性文件的SpringBoot2.0。我想将它拆分为单独的属性文件,因为... 查看详情

在 Jackson / Spring Boot 中测试自定义 Json Deserializer

】在Jackson/SpringBoot中测试自定义JsonDeserializer【英文标题】:TestingcustomJsonDeserializerinJackson/SpringBoot【发布时间】:2020-05-2012:02:56【问题描述】:我正在尝试将单元测试写入自定义反序列化程序,该反序列化程序使用带有@Autowired参... 查看详情

为啥使用 webflux 进行 spring boot 测试会忽略自定义 jackson 模块

】为啥使用webflux进行springboot测试会忽略自定义jackson模块【英文标题】:Whydoesspringboottestwithwebfluxignorecustomjacksonmodule为什么使用webflux进行springboot测试会忽略自定义jackson模块【发布时间】:2018-10-2001:54:40【问题描述】:我正在使... 查看详情

Spring Boot 自定义 http 错误响应?

】SpringBoot自定义http错误响应?【英文标题】:SpringBootcustomizehttperrorresponse?【发布时间】:2014-12-0122:15:44【问题描述】:如果SpringBootweb应用发生异常,如何自定义响应状态码和响应体中的数据?我创建了一个Web应用程序,如果... 查看详情

如何为我的 Spring Boot 控制器执行单元测试?

】如何为我的SpringBoot控制器执行单元测试?【英文标题】:Howtoperformunittestsformyspringbootcontroller?【发布时间】:2018-06-0314:24:25【问题描述】:我是TDD的新手,目前我正在学习一些关于如何为我的SpringBootAPI编写自动化测试的知识... 查看详情

Spring boot:如何自定义禁止的错误 json

】Springboot:如何自定义禁止的错误json【英文标题】:Springboot:HowcouldIcustomizetheforbiddenerrorjson【发布时间】:2019-03-0120:29:20【问题描述】:我想知道是否可以自定义以下禁止的JSON错误:实际反应"timestamp":"2018-09-26T06:11:05.047+0000","st... 查看详情

如何为 ZuulException 自定义 Spring Boot 控制器 API 响应

】如何为ZuulException自定义SpringBoot控制器API响应【英文标题】:HowtocustomizeSpringbootcontrollerAPIresponseforZuulException【发布时间】:2019-04-1505:24:16【问题描述】:我们正在为RESTAPI使用Zuul、Eureka和SpringBoot应用程序服务。假设我的springboo... 查看详情

抛出异常时,Spring Boot 不显示自定义错误

】抛出异常时,SpringBoot不显示自定义错误【英文标题】:Springbootdoesnotshowcustomerrorwhenexceptionisthrown【发布时间】:2020-03-1518:30:00【问题描述】:我对Java/Spring领域相当陌生,我正在尝试在我的SpringBoot应用程序中使用@ControllerAdvice... 查看详情

如何测试 Spring Boot Controller 的错误输出?

...题描述】:我已经实现了一个带有简单请求/响应的简单控制器。控制器@RestController@RequestMapping("/")publicclassHelloWorldControllerextendsAbs 查看详情

在 Spring Boot 中使用自定义错误 html 文件

】在SpringBoot中使用自定义错误html文件【英文标题】:Usingacustomerrorhtmlfileinspringboot【发布时间】:2019-05-0818:00:45【问题描述】:我有一个/error的url映射到我的errorPage.html,但它没有重定向到这个,我得到了正常的默认springboot错误... 查看详情

Spring Boot REST API 版本控制的自定义标头方法

】SpringBootRESTAPI版本控制的自定义标头方法【英文标题】:CustomHeaderApproachforSpringBootRESTAPIversioning【发布时间】:2020-04-2905:47:02【问题描述】:我希望实现使用自定义标头使用SpringBoot和Swagger对RESTAPI进行版本控制。我浏览了许多... 查看详情