Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 516|回复: 0

springBoot(5)---单元测试,全局异常

[复制链接]
  • TA的每日心情
    奋斗
    4 天前
  • 签到天数: 789 天

    [LV.10]以坛为家III

    2049

    主题

    2107

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    722638
    发表于 2021-7-6 03:06:58 | 显示全部楼层 |阅读模式

    单元测试,全局异常

     

    一、单元测试

    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】

     

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-9-10 08:22 , Processed in 1.004902 second(s), 29 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表