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】

原文地址:https://www.cnblogs.com/qdhxhz/p/9038436.html

时间: 2024-08-28 21:40:13

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

springboot编程之全局异常捕获

springboot编程之全局异常捕获 1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice, 在方法上注解@ExceptionHandler(value = Exception.class),Exception.class表示拦截所有的异常信息 package com.imooc.web.controller; import com.imooc.exception.UserNotExistException; import org.spr

Eclipse搭建springboot项目(六)全局异常

知识点: 1.SpringBoot2.x服务端异常和SpringBoot配置全局异常 1).默认异常测试 int i = 1/0,不友好 2).异常注解介绍 @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody //捕获全局异常,处理所有不可知的异常 @ExceptionHandler(value=Exception.class) 2.SpringBoot2.x配置全局异常返回自定义异常和错误页面跳转

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

1.创建GlobalExceptionHandler.java,在类上注解@ControllerAdvice,在方法上注解@ExceptionHandler(value = Exception.class),Exception.class表示拦截所有的异常信息 package com.rick.common.handler; import com.alibaba.fastjson.JSON;import com.alibaba.fastjson.util.IOUtils;import com.r

[四]SpringBoot 之 捕捉全局异常

在class注解上@ControllerAdvice, 在方法上注解上@ExceptionHandler(value = Exception.class),具体代码如下: package me.shijunjie.controller; import javax.servlet.http.HttpServletRequest; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springfra

SpringBoot(6) SpringBoot配置全局异常

1.全局异常 @ControllerAdvice 如果是返回json数据 则用 RestControllerAdvice,就可以不加 @ResponseBody //捕获全局异常,处理所有不可知的异常 @ExceptionHandler(value=Exception.class) 1 @RestControllerAdvice 2 public class CustomExtHandler { 3 4 private static final Logger LOG = LoggerFactor

SpringBoot:如何优雅地处理全局异常?

SpringBoot:如何优雅地处理全局异常? 之前用springboot的时候,只知道捕获异常使用try{}catch,一个接口一个try{}catch,这也是大多数开发人员异常处理的常用方式,虽然屡试不爽,但会造成一个问题,就是一个Controller下面,满屏幕的try{}catch,看着一点都不优雅,一点都不符合×××的气质,憋了这么久,×××今天终于决定对所有异常实施统一处理的方案. 开发准备 JDK8.正常的springboot项目 代码编写 通用异常处理 其实Spring系列的项目

springboot捕获全局异常和配置多数据源

目录 配置多数据源 写两个数据源的配置类. @(springboot捕获全局异常和配置多数据源) 捕获全局异常是在项目运行期间如果调用的某一个方法出现了运行时异常,则会捕获,并且给出回馈. 首先需要建一个包,包里新建一个捕获异常类GlobalExceptionHandler.前提是springboot的启动类的扫描注解ComponentScan()要扫描到. /** * 用于捕获全局异常 */ @ControllerAdvice//控制器切面 public class GlobalExcepti

【spring】-- springboot配置全局异常处理器

一.为什么要使用全局异常处理器? 什么是全局异常处理器? 就是把错误异常统一处理的方法. 应用场景: 1.当你使用jsr303参数校验器,如果参数校验不通过会抛异常,而且无法使用try-catch语句直接捕获,这时可以使用全局异常处理器来捕捉该异常. 2.当你自定义了一个异常类,可以在全局异常处理器中来捕捉该异常.(当然也可以直接在抛出异常处直接捕获,但是这样需要在每一个抛出的地方都写一次捕获代码,看起来不够美观且复用性不强,其他异常同理). 所有异常都可以在全局异常处理器中捕获进行统一处理 二

Spring Boot 中全局异常处理器

Spring Boot 中全局异常处理器,就是把错误异常统一处理的方法.等价于Springmvc中的异常处理器. 步骤一:基于前面的springBoot入门小demo修改 步骤二:修改HelloController类 修改HelloController,使得访问/hello一定会产生异常: some exception package cn.xdf.springboot.web; import java.text.DateFormat; import java.util.Date; import