单元测试,全局异常

一、单元测试

1.基础版

1、引入相关依赖

  1. <!--springboot程序测试依赖,如果是自动创建项目默认添加-->
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-test</artifactId>
  5. <scope>test</scope>
  6. </dependency>

2:关键注解:@RunWith @SpringBootTest

  1. import junit.framework.TestCase;
  2.  
  3. import org.junit.After;
  4. import org.junit.Before;
  5. import org.junit.Test;
  6. import org.junit.runner.RunWith;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9.  
  10. @RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
  11. @SpringBootTest(classes={SpringbootstudyApplication.class})//启动整个springboot工程
  12. public class SpringBootTestDemo {
  13.  
  14. @Test
  15. public void testOne(){
  16. System.out.println("test hello 1");
  17. TestCase.assertEquals(1, 1);
  18.  
  19. }
  20. @Test
  21. public void testTwo(){
  22. System.out.println("test hello 2");
  23. TestCase.assertEquals(1, 1);
  24.  
  25. }
  26.  
  27. @Before
  28. public void testBefore(){
  29. System.out.println("before");
  30. }
  31.  
  32. @After
  33. public void testAfter(){
  34. System.out.println("after");
  35. }
  36. }

输出结果:

2.MockMvc

MockMvc类的使用和模拟Http请求实战

TestController

  1. import org.springframework.web.bind.annotation.RequestMapping;
  2. import org.springframework.web.bind.annotation.RestController;
  3.  
  4. @RestController
  5. public class TestController {
  6.  
  7. @RequestMapping("/vq/test")
  8. public String getTest(){
  9.  
  10. return"我是测试返回值";
  11. }
  12. }

MockMvcTestDemo

  1. import org.junit.Test;
  2. import org.junit.runner.RunWith;
  3. import org.springframework.beans.factory.annotation.Autowired;
  4. import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
  5. import org.springframework.boot.test.context.SpringBootTest;
  6. import org.springframework.test.context.junit4.SpringRunner;
  7. import org.springframework.test.web.servlet.MockMvc;
  8. import org.springframework.test.web.servlet.MvcResult;
  9. import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
  10. import org.springframework.test.web.servlet.result.MockMvcResultMatchers;
  11.  
  12. /**
  13. * 功能描述:测试mockmvc类
  14. *
  15. */
  16. @RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
  17. @SpringBootTest(classes={SpringbootstudyApplication.class}) //启动整个springboot工程
  18. @AutoConfigureMockMvc
  19. public class MockMvcTestDemo {
  20.  
  21. @Autowired
  22. private MockMvc mockMvc;
  23.  
  24. @Test
  25. public void apiTest() throws Exception {
  26.  
  27. MvcResult mvcResult = mockMvc.perform( MockMvcRequestBuilders.get("/vq/test") ).
  28. andExpect( MockMvcResultMatchers.status().isOk() ).andReturn();
  29. int status = mvcResult.getResponse().getStatus();
  30. System.out.println(status);
  31.  
  32. }
  33. }

结果:返回200状态码

总结,关键注解:

  1. @RunWith(SpringRunner.class) //底层用junit SpringJUnit4ClassRunner
  2. @SpringBootTest(classes={SpringbootstudyApplication.class}) //启动整个springboot工程
  3. @AutoConfigureMockMvc

二、配置全局异常

首先springboot自带异常是不友好的。

举例

  1. @RequestMapping(value = "/api/v1/test_ext")
  2. public Object index() {
  3. int i= 1/0;
  4. return new User(11, "sfsfds", "1000000", new Date());
  5. } 

页面

1、配置全局异常

  1. import java.util.HashMap;
  2. import java.util.Map;
  3.  
  4. import javax.servlet.http.HttpServletRequest;
  5.  
  6. import org.slf4j.Logger;
  7. import org.slf4j.LoggerFactory;
  8. import org.springframework.web.bind.annotation.ExceptionHandler;
  9. import org.springframework.web.bind.annotation.RestControllerAdvice;
  10.  
  11. //添加全局异常注解
  12. @RestControllerAdvice
  13. public class CustomExtHandler {
  14.  
  15. private static final Logger LOG = LoggerFactory.getLogger(CustomExtHandler.class);
  16.  
  17. //捕获全局异常,处理所有不可知的异常
  18. @ExceptionHandler(value=Exception.class)
  19. //@ResponseBody
  20. Object handleException(Exception e,HttpServletRequest request){
  21. LOG.error("url {}, msg {}",request.getRequestURL(), e.getMessage());
  22. Map<String, Object> map = new HashMap<>();
  23. map.put("code", 100);
  24. map.put("msg", e.getMessage());
  25. map.put("url", request.getRequestURL());
  26. return map;
  27. }
  28. }

在看页面:

关键注解:

  1. @RestControllerAdvice //全局注解

@ExceptionHandler(value=Exception.class)  //捕获不同异常,这里捕获是Exception异常,你也可以指定其它异常

2.自定义异常

在 Java 中你可以自定义异常。编写自己的异常类时需要记住下面的几点。

  • 所有异常都必须是 Throwable 的子类。
  • 如果希望写一个检查性异常类,则需要继承 Exception 类。
  • 如果你想写一个运行时异常类,那么需要继承 RuntimeException 类。
  1. 1.自定义MyException异常
  1. /**
  2. * 功能描述:自定义异常类
  3. *
  4. */
  5. public class MyException extends RuntimeException {
  6.  
  7. private static final long serialVersionUID = 1L;
  8.  
  9. public MyException(String code, String msg) {
  10. this.code = code;
  11. this.msg = msg;
  12. }
  13.  
  14. private String code;
  15. private String msg;
  16. public String getCode() {
  17. return code;
  18. }
  19. public void setCode(String code) {
  20. this.code = code;
  21. }
  22. public String getMsg() {
  23. return msg;
  24. }
  25. public void setMsg(String msg) {
  26. this.msg = msg;
  27. }
  28.  
  29. }

controller类

  1. /**
  2. * 功能描述:模拟自定义异常
  3. */
  4. @RequestMapping("/api/v1/myext")
  5. public Object myexc(){
  6. //直接抛出异常
  7. throw new MyException("499", "my ext异常");
  8. }

页面

想太多,做太少,中间的落差就是烦恼。想没有烦恼,要么别想,要么多做。上尉【7】

springBoot(5)---单元测试,全局异常的更多相关文章

  1. springboot编程之全局异常捕获

    springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler( ...

  2. 【快学springboot】5.全局异常捕获,异常流处理业务逻辑

    前言 上一篇文章说到,参数校验,往往需要和全局的异常拦截器来配套使用,使得返回的数据结构永远是保持一致的.参数异常springboot默认的返回结构: { "timestamp": ...

  3. 170621、springboot编程之全局异常捕获

    1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice,在方法上注解@ExceptionHandler(value = Exception.cla ...

  4. (五)SpringBoot如何定义全局异常

    一:添加业务类异常 创建ServiceException package com.example.demo.core.ret; import java.io.Serializable; /** * @ ...

  5. [四]SpringBoot 之 捕捉全局异常

    在class注解上@ControllerAdvice, 在方法上注解上@ExceptionHandler(value = Exception.class),具体代码如下: package me.shi ...

  6. Springboot项目全局异常统一处理

    转自https://blog.csdn.net/hao_kkkkk/article/details/80538955 最近在做项目时需要对异常进行全局统一处理,主要是一些分类入库以及记录日志等,因为项 ...

  7. SpringBoot优雅的全局异常处理

    前言 本篇文章主要介绍的是SpringBoot项目进行全局异常的处理. SpringBoot全局异常准备 说明:如果想直接获取工程那么可以直接跳到底部,通过链接下载工程代码. 开发准备 环境要求 JD ...

  8. (办公)springboot配置全局异常

    项目用到了springboot,本来很高兴,但是项目里什么东西都没有,验证,全局异常这些都需要自己区配置.最近springboot用的还是蛮多的,我还是做事情,把经验发表一下.全局统一的异常,首先异常 ...

  9. SpringBoot(6) SpringBoot配置全局异常

    1.全局异常 @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody //捕获全局异常,处理所有不可知的异常 ...

随机推荐

  1. Html与CSS学习书单

    1.Head First HTML与CSS(第二版) 豆瓣详情 这本书非常适合入门学习HTML与CSS它的内容不一定详实,但一定是你入门的首选.作为一本引进 图书翻译尚可.目前豆瓣评分9.3.

  2. Newtonsoft.Json 时间格式化

    时间序列化经常多个T:“2017-01-23T00:00:00” 解决方案: 日期格式化输出,指定IsoDateTimeConverter的DateTimeFormat即可 IsoDateTimeCo ...

  3. django中的modelform和modelfoemset

    一. ModelForm ModelForm是根据Model来定制的Form 二. ModelForm的创建 from django import forms from app import mode ...

  4. 第一次OO总结

    作业1——多项式加减法 看到这个名字就开始瑟瑟发抖了,毕竟一年前用C语言让我写这么一个程序都很头疼,什么堆栈啊还有结构都稀里糊涂的,更别说用一个完全没接触过的语言来完成最简单的一次作业.像我这样越老心 ...

  5. python 方法

    1.首先运行python交互模式 输入 python 2.定义一个有序的集合 相当于js中的数组它里面有一些增删改查的方法 1. 定义一个数组 >>> ww = ['1','2',' ...

  6. [转]数据库中间件 MyCAT源码分析——跨库两表Join

    1. 概述 2. 主流程 3. ShareJoin 3.1 JoinParser 3.2 ShareJoin.processSQL(...) 3.3 BatchSQLJob 3.4 ShareDBJo ...

  7. sublime text3如何在浏览器预览?

    插件: view-in-browser CTRL + ALT + V 打开浏览器 默认打开firefox,settings里面可修改. Sublime Text - View In Browser V ...

  8. bzoj4445(半平面交)

    列出式子对一下然后上半平面交 #include<iostream> #include<cstring> #include<cmath> #include<cs ...

  9. VUE最佳实践

    vuex 作为model数据请求由action来获取,页面组建级的发送action,返回promise给组建使用,如果使用周期较长需comit到mutation保存到state. 数据分模块,根据业务 ...

  10. 2018/9/6 spring框架的整理

    spring知识的巩固整理AOP和ioc概念,以及了解到了为何要使用spring框架的目的,作用:变换资源获取的方向.更像是按需所求.配置bean的方式:利用XML的方式,基于注解的方式两种.1通过全 ...