Springboot2.0单元测试和自定义异常处理(Springboot2.0系列-三)

1、@SpringBootTest单元测试

简介:SpringBoot的单元测试

1)、引入相关依赖


    
        org.springframework.boot
        spring-boot-starter-test
        test
    

2)、使用

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

2、SpringBoot测试之MockMvc

简介:MockMvc类的使用和模拟Http请求

1)、增加类注解 @AutoConfigureMockMvc
@SpringBootTest(classes={XdclassApplication.class})

2)、相关API

perform:执行一个RequestBuilder请求
andExpect:添加ResultMatcher->MockMvcResultMatchers验证规则
andReturn:最后返回相应的MvcResult->Response

3、SpringBoot2.x个性化启动banner设置和debug日志

简介:自定义应用启动的趣味性日志图标和查看调试日志

1、启动获取更多信息 java -jar xxx.jar –debug

2、修改启动的banner信息

1)在类路径下增加一个banner.txt,里面是启动要输出的信息
2)在applicatoin.properties增加banner文件的路径地址 :spring.banner.location=banner.txt

3)官网地址 https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#boot-features-banners

4、启动容器和第三方性能测试工具

1)使用Jmter测试工具测试性能,QPS,TPS,RT

2)启动容器:常见的有tomcat,jetty,undertow,性能比较见下:
https://examples.javacodegeeks.com/enterprise-java/spring/tomcat-vs-jetty-vs-undertow-comparison-of-spring-boot-embedded-servlet-containers/

5、SpringBoot2.x配置全局异常

简介:服务端异常讲解和SpringBoot配置全局异常

1、默认异常测试 int i = 1/0,不友好

2、异常注解

@ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody

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

6、SpringBoot2.x配置全局异常返回自定义页面

简介:使用SpringBoot自定义异常和错误页面跳转

1、返回自定义异常界面,需要引入thymeleaf依赖


    org.springframework.boot
    spring-boot-starter-thymeleaf

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

你可能感兴趣的:(java,springboot2.0,异常处理,单元测试)