zoukankan      html  css  js  c++  java
  • springboot(5)单元测试及MockMVC类的使用及自定义异常处理

    springboot @SpringBootTest单元测试
    1、引入相关依赖
    <!--springboot程序测试依赖,如果是自动创建项目默认添加-->
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    </dependency>


    2、使用
    @RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
    @SpringBootTest(classes={XdclassApplication.class})//启动整个springboot工程
    public class SpringBootTests { }

    SpringBoot测试 MockMvc类的使用
    1、增加类注解 @AutoConfigureMockMvc
    @SpringBootTest(classes={XdclassApplication.class})
    2、相关API
    perform:执行一个RequestBuilder请求
    andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
    andReturn:最后返回相应的MvcResult->Response


    springboot2.x配置全局异常处理
    1、默认异常测试 int i = 1/0,不友好

    2、异常注解介绍
    @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody

    //捕获全局异常,处理所有不可知的异常
    @ExceptionHandler(value=Exception.class)

    springboot2.x自定义全局异常
    1、返回自定义异常界面,需要引入thymeleaf依赖
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>


    2、resource目录下新建templates,并新建error.html
    ModelAndView modelAndView = new ModelAndView();
    modelAndView.setViewName("error.html");
    modelAndView.addObject("msg", e.getMessage());
    return modelAndView;


    https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-error-handling

  • 相关阅读:
    [extjs] ExtJs4.2 Form 表单提交
    [java ] java.util.zip.ZipException: error in opening zip file
    Oracle 11g 执行计划管理1
    Oracle 分区表的统计信息实例
    Oracle 手动收集统计信息
    Oracle 10g 之自动收集统计信息
    Oracle 11g 之自动收集统计信息
    Oracle 11gR2 RAC修改SCAN IP
    共享内存shared pool (6):追踪sql语句
    共享内存shared pool (5):详解一条SQL在library cache中解析
  • 原文地址:https://www.cnblogs.com/suncm/p/10893904.html
Copyright © 2011-2022 走看看