springBoot(5)---单元测试,全局异常
单元测试,全局异常
一、单元测试
1.基础版
1、引入相关依赖
<!--springboot程序测试依赖,如果是自动创建项目默认添加-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2:关键注解:@RunWith @SpringBootTest
import junit.framework.TestCase; import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner; @RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={SpringbootstudyApplication.class})//启动整个springboot工程
public class SpringBootTestDemo { @Test
public void testOne(){
System.out.println("test hello 1");
TestCase.assertEquals(1, 1); }
@Test
public void testTwo(){
System.out.println("test hello 2");
TestCase.assertEquals(1, 1); } @Before
public void testBefore(){
System.out.println("before");
} @After
public void testAfter(){
System.out.println("after");
}
}
输出结果:

2.MockMvc
MockMvc类的使用和模拟Http请求实战
TestController
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; @RestController
public class TestController { @RequestMapping("/vq/test")
public String getTest(){ return"我是测试返回值";
}
}
MockMvcTestDemo
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers; /**
* 功能描述:测试mockmvc类
*
*/
@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={SpringbootstudyApplication.class}) //启动整个springboot工程
@AutoConfigureMockMvc
public class MockMvcTestDemo { @Autowired
private MockMvc mockMvc; @Test
public void apiTest() throws Exception { MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/vq/test") ).
andExpect( MockMvcResultMatchers.status().isOk() ).andReturn();
int status = mvcResult.getResponse().getStatus();
System.out.println(status); }
}
结果:返回200状态码

总结,关键注解:
@RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
@SpringBootTest(classes={SpringbootstudyApplication.class}) //启动整个springboot工程
@AutoConfigureMockMvc
二、配置全局异常
首先springboot自带异常是不友好的。
举例
@RequestMapping(value = "/api/v1/test_ext")
public Object index() {
int i= 1/0;
return new User(11, "sfsfds", "1000000", new Date());
}
页面

1、配置全局异常
import java.util.HashMap;
import java.util.Map; import javax.servlet.http.HttpServletRequest; import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice; //添加全局异常注解
@RestControllerAdvice
public class CustomExtHandler { private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class); //捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)
//@ResponseBody
Object handleException(Exception e,HttpServletRequest request){
LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
Map<String, Object> map = new HashMap<>();
map.put("code", 100);
map.put("msg", e.getMessage());
map.put("url", request.getRequestURL());
return map;
}
}
在看页面:

关键注解:
@RestControllerAdvice //全局注解
@ExceptionHandler(value=Exception.class) //捕获不同异常,这里捕获是Exception异常,你也可以指定其它异常
2.自定义异常
在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。
- 所有异常都必须是 Throwable 的子类。
- 如果希望写一个检查性异常类,则需要继承 Exception 类。
- 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。
1.自定义MyException异常
/**
* 功能描述:自定义异常类
*
*/
public class MyException extends RuntimeException { private static final long serialVersionUID = 1L; public MyException(String code, String msg) {
this.code = code;
this.msg = msg;
} private String code;
private String msg;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
} }
controller类
/**
* 功能描述:模拟自定义异常
*/
@RequestMapping("/api/v1/myext")
public Object myexc(){
//直接抛出异常
throw new MyException("499", "my ext异常");
}
页面

想太多,做太少,中间的落差就是烦恼。想没有烦恼,要么别想,要么多做。上尉【7】
springBoot(5)---单元测试,全局异常的更多相关文章
- springboot编程之全局异常捕获
springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler( ...
- 【快学springboot】5.全局异常捕获,异常流处理业务逻辑
前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...
- 170621、springboot编程之全局异常捕获
1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice,在方法上注解@ExceptionHandler(value = Exception.cla ...
- (五)SpringBoot如何定义全局异常
一:添加业务类异常 创建ServiceException package com.example.demo.core.ret; import java.io.Serializable; /** * @ ...
- [四]SpringBoot 之 捕捉全局异常
在class注解上@ControllerAdvice, 在方法上注解上@ExceptionHandler(value = Exception.class),具体代码如下: package me.shi ...
- Springboot项目全局异常统一处理
转自https://blog.csdn.net/hao_kkkkk/article/details/80538955 最近在做项目时需要对异常进行全局统一处理,主要是一些分类入库以及记录日志等,因为项 ...
- SpringBoot优雅的全局异常处理
前言 本篇文章主要介绍的是SpringBoot项目进行全局异常的处理. SpringBoot全局异常准备 说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码. 开发准备 环境要求 JD ...
- (办公)springboot配置全局异常
项目用到了springboot,本来很高兴,但是项目里什么东西都没有,验证,全局异常这些都需要自己区配置.最近springboot用的还是蛮多的,我还是做事情,把经验发表一下.全局统一的异常,首先异常 ...
- SpringBoot(6) SpringBoot配置全局异常
1.全局异常 @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody //捕获全局异常,处理所有不可知的异常 ...
随机推荐
- java之路 定义个一初始值 取它 个位 十位 百位 千位。。的数值。
class Demo{ public static void main(String[] args){ int i =2584; //do{ int g = i%10; int s = (i%100) ...
- python第三天基础之字符编码
一 了解字符编码的知识储备 1. 文本编辑器存取文件的原理(nodepad++,pycharm,word) 打开编辑器就打开了启动了一个进程,是在内存中的,所以在编辑器编写的内容也都是存放与内存中的, ...
- 09-JS的事件流的概念(重点)
在学习jQuery的事件之前,大家必须要对JS的事件有所了解.看下文 事件的概念 HTML中与javascript交互是通过事件驱动来实现的,例如鼠标点击事件.页面的滚动事件onscroll等等,可以 ...
- 生成图形化html报告
生成图形化html报告: 1.从cmd 进入执行测试文件 2.执行该命令:jmeter -n -t <test JMX file> -l <test log file> -e ...
- C++输出格式
C++输出格式 C++中默认输出有效位数是6位,即 则输出: 221.111.11011199967 //6位有效数字,自动截取保存六位1.99967e+006 //六位以上且无法省略显示将会变为指数 ...
- 继承Thread类和实现Runnable接口
一.采用继承Thread类方法的特点: 优势:编写简单,如果需要访问当前的线程,只需要使用this,并可以在run()方法中调用其他线程的方法: 劣势:线程已经继承了Thread类,不能继承其他的父类 ...
- CCNA学前基础一
网络设备: 集线器:集线器就是一种采用共享式工作状态的设备.Hub将信号放大后传输给其他端口,即传输线路是共享的. 交换机:用于连接终端设备,和基本的安全功能还有广播域的隔离.优点实现多用户同时访问, ...
- UltraISO制作CentOS 7.6 U盘引导安装盘
一.制作准备: 1.UltraISO下载安装 2.CentOS镜像文件下载(阿里镜像下载) 二.制作引导盘: 1.电脑插入U盘 2.UltraISO加载镜像文件: 文件->打开->选择对应 ...
- 架构(四)Git简介,安装以及相关命令SourceTree
一 Git介绍 1.1 Git是什么? Git是一个分布式版本控制软件: 版本控制:假如开发人员开发了一个a功能,结果项目经理觉得不够需要修改,开发人员又改成了b功能,后来又改成了c功能,但是最终项目 ...
- Oracle数据库用EF操作的示例
Using EF Oracle Sample Provider with EDM Designer (from msdn) Many people are asking if it is possi ...