Springboot2.X测试应用

.Springboot2.X测试应用
需求分析->设计->开发->测试->上线

1.测试里面的种类
1.1 单元测试
完成最小的软件设计单元的验证工作,目标是确保模块被正确的编码
1.2 黑盒测试
不考虑内部结构,主要测试功能十分满足需求
1.3 白盒测试
针对代码级别,测试开发工程师一般具备白盒测试能力,针对程序内部的逻辑结构进行代码级别的测试
1.4 回归测试
对原先提出的缺陷进行二次验证,开发人员修复后进行二次的验证
1.5 集成测试
测试模块和模块之间的整合,且测试主要的业务功能
1.6 系统测试
针对整个产品系统进行的测试,验证系统是否满足产品业务需求

2.SpringBoot2.x的单元测试

引入相关依赖
	<!--springboot程序测试依赖,如果是自动创建项目默认添加-->
	 <dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<scope>test</scope>
	</dependency>

	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>4.12</version>
		<scope>test</scope>
	</dependency>

配置相关注解
@RunWith(SpringRunner.class):底层用junit SpringJUnit4ClassRunner
Test测试类要使用注入的类,比如@Autowired注入的类,有了@RunWith(SpringRunner.class)这些类才能实例化到spring容器中,自动注入才能生效,
不然直接一个NullPointerExecption

@SpringBootTest(classes={DemoProjactApplication.class})//启动整个springboot工程
	public class TestVideo {
			
		@Before
		public void testOne(){
			System.out.println("这是测试 before ");
		}

		@Test
		public void testTwo1(){
			System.out.println("这是测试 test1 ");
			//断言
			TestCase.assertEquals(1,3);
		}

		@Test
		public void testTwo2(){
			System.out.println("这是测试 test2 ");
		}

		@After
		public void testThree(){
			System.out.println("这是测试 after ");
		}

	}

常用单元测试的注解:@before、@Test、@After
断言:判断程序结果是否符合预期 TestCase.assertXXX

3.springboot的MockMvc调用api层接口
增加类注解 @AutoConfigureMockMvc、 注入一个MockMvc类
3.1 MockMvc是什么
MockMvc是Spring Test提供的功能,可是实现对Controller层(API)做测试,也就是不必启动工程就能测试Controller接口。
MockMvc实现了对Http请求的模拟,能够直接使用网络的形式,转换到Controller的调用,这样可以使得测试速度快、不依赖网络环境。而且提供了一套验证的工具,
这样可以使得请求的验证统一而且很方便。
3.2 引入起步依赖


org.springframework.boot
spring-boot-starter-web

	<!-- MockMvc 是Spring Test 提供的功能, 需要添加spring test的依赖jar包 -->
	<!-- 在Spring Boot Test中,实现了MockMvc的自动配置,使得我们可以通过@AutoConfigureMockMvc注解开启MockMvc的配置.直接通过@Autowired注入MockMvc使用。 -->
	<dependency>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-test</artifactId>
		<exclusions>
			<exclusion>
				<groupId>org.junit.vintage</groupId>
				<artifactId>junit-vintage-engine</artifactId>
			</exclusion>
		</exclusions>
	</dependency>

	<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
	<dependency>
		<groupId>org.mockito</groupId>
		<artifactId>mockito-all</artifactId>
		<version>2.0.2-beta</version>
		<scope>test</scope>
	</dependency>

不能引入spring-boot-starter-security起步依赖,否则运行测试时会报错Full authentication is required to access this resource

3.3 实例
@RunWith(SpringRunner.class)  //底层用junit  SpringJUnit4ClassRunner
	@SpringBootTest(classes={DemoProjactApplication.class})//启动整个springboot工程
	@AutoConfigureMockMvc
	public class TestApi {

		@Autowired
		private MockMvc mockMvc;

		@Test
		public void testVideoListApi() throws Exception {
			//MockMvcRequestBuilders 模拟http请求的构建器
			//MockMvcRequestBuilders.get  请求方式
			MvcResult mvcResult =  mockMvc.perform(MockMvcRequestBuilders.get("/api/v1/pub/video/list"))
                .andExpect(MockMvcResultMatchers.status().isOk()).andReturn();
		   int status = mvcResult.getResponse().getStatus();
		   System.out.println(status);
			//会乱码
			//String result = mvcResult.getResponse().getContentAsString();

			// 使用下面这个,增加 编码 说明,就不会乱码打印
			String result = mvcResult.getResponse().getContentAsString(Charset.forName("utf-8"));

		   System.out.println(result);
		}
	}

3.4 注解解释
@SpringBootTest注解:是SpringBoot自1.4.0版本开始引入的一个用于测试的注解,来提供SpringBoot单元测试环境支持。
SpringBoot单元测试环境支持 就是说 可以取到spring中的容器的实例,如果配置了@Autowired那么就自动将对象注入。如果你使用的JUnit版本如果是JUnit4
不要忘记在测试类上添加@RunWith(SpringJUnit4ClassRunner.class),JUnit 5就不需要了。
注:这是SpringBoot Test的功能 import org.springframework.boot.test.context.SpringBootTest;

@RunWith(SpringJUnit4ClassRunner.class),让测试运行于Spring测试环境,以便在测试开始的时候自动创建Spring的应用上下文
	import org.junit.runner.RunWith;
	import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
	Spring Boot 2.2之后 ,也就是junit5中 启动Spring Boot 测试环境 需要@SpringBootTest 一个注解就好。
	Spring Boot 2.2之前 ,也就是junit4中 启动 @RunWith(SpringJUnit4ClassRunner.class) 和 @SpringBootTest 两个注解一块使用。否则@Autowired注入的会是null 参考解决SpringBoot单元测试@Autowired不生效问题
	
	@EnableWebMvc注解:为该应用添加SpringMVC的功能,即添加之后可以在项目中,可以使用@RequestMapping等注解来定义请求处理与请求uri的映射和其他SpringMvc提供的功能
	注:这是spring web的功能 import org.springframework.web.servlet.config.annotation.EnableWebMvc;
	
	@AutoConfigureMockMvc注解 :表示 MockMvc交给Spring容器管理,开启自动配置MockMvc 。我们需要使用时 只要注入就可以了。如果没有这个注解,需要自己根据应用上下文创建 管理MockMvc对象。有了这个注解,只要注入MockMvc就可以使用了。
	注:这是Spring test的功能 import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
	
	@Test注解 在junit5中 是 import org.junit.jupiter.api.Test  而不是import org.junit.Test;
	
	3.5 MockMvc解释: 执行请求 并返回ResultActions实例,添加断言等
	mockMvc.perform执行一个请求,会自动执行SpringMVC的流程并映射到相应的控制器执行处理,返回一个ResultActions实例
	MockMvcRequestBuilders.get("/student/findAll") 根据uri模板和uri变量值 构造一个GET,PUT,POST,DELETE等请求,Post请求就用.post方法
	contentType(MediaType.APPLICATION_JSON_UTF8)代表发送端发送的数据格式是application/json;charset=UTF-8
	accept(MediaType.APPLICATION_JSON_UTF8)代表客户端希望接受的数据类型为application/json;charset=UTF-8
	ResultActions.andExpect添加执行完成后的断言
	ResultActions.andExpect(MockMvcResultMatchers.status().isOk())方法看请求的状态响应码是否为200如果不是则抛异常,测试不通过
	ResultActions.andExpect(MockMvcResultMatchers.jsonPath(“$.author”).value(“嘟嘟MD独立博客”))这里jsonPath用来获取author字段比对是否为嘟嘟MD独立博客,不是就测试不通过
	ResultActions.andDo添加一个结果处理器,表示要对结果做点什么事情,比如此处使用MockMvcResultHandlers.print()输出整个响应结果信息

  1. Springboot2.X全局异常处理
    统一的错误页面或者错误码、对用户更友好
    Springboot2.X怎么在项目中配置全局异常
    4.1 类添加注解
    @ControllerAdvice,如果需要返回json数据,则方法需要加@ResponseBody
    @RestControllerAdvice, 默认返回json数据,方法不需要加@ResponseBody

4.2方法添加处理器
捕获全局异常,处理所有不可知的异常
@ExceptionHandler(value=Exception.class)

4.3 实例

package com.funi.demoprojact.handler;

import com.funi.demoprojact.utils.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@RestControllerAdvice
public class CustomExtHandler {

   @ExceptionHandler(Exception.class)
    JsonData handlerException(Exception e, HttpServletRequest request){
        return JsonData.buildError(-2,"服务器异常");
   }
}
package com.funi.demoprojact.utils;

/**
 * 接口返回工具类
 */
public class JsonData {
    private int code;
    private Object data;
    private String msg;

    public JsonData(){}
    public JsonData(int code,Object data){
        this.code = code;
        this.data = data;
    }
    public JsonData(int code,Object data,String msg){
        this.code = code;
        this.data = data;
        this.msg = msg;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public static JsonData buildSuccess(int code, Object data){
        return new JsonData(code,data);
    }
    public static JsonData buildError(int code,String msg){
        return new JsonData(code,"",msg);
    }

    @Override
    public String toString() {
        return "JsonData{" +
                "code=" + code +
                ", data=" + data +
                ", msg='" + msg + '\'' +
                '}';
    }
}

4.4 SpringBoot自定义异常和错误页面跳转实战
返回自定义异常界面,需要引入thymeleaf依赖(非必须,如果是简单的html界面则不用)

		   <groupId>org.springframework.boot</groupId>
		   <artifactId>spring-boot-starter-thymeleaf</artifactId>
	</dependency>

package com.funi.demoprojact.handler;

import com.funi.demoprojact.utils.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class CustomExtHandler {
    @ExceptionHandler(Exception.class)
    ModelAndView handlerException(Exception e, HttpServletRequest request){
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("error.html");
        modelAndView.addObject("msgExt", e.getMessage());
        modelAndView.addObject("msg", "服务器异常");
        return modelAndView;
    }
}

在src\main\resources\templates\创建 error.html

<html  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
SpringBoot学习开始   自定义模板

<p th:text="${msg}"/>

<!--<p th:text="${msgExt}"/>-->
</body>

默认配置文件中加 classpath:/templates/ spring.web.resources.static-locations= classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值