文章目录

  • 一、junit断言
  • 二、测试模块
  • 三、使用Mockito作为桩模块
  • 四、使用mockMvc测试web层
  • 五、批量测试和测试覆盖率

参考视频: 用Spring Boot编写RESTful API
参考链接: Spring Boot构建RESTful API与单元测试
参考链接: Junit自动单元测试以及测试覆盖率简单使用

一、junit断言

函数 作用
TestCase.assertTrue 判断条件是否为真
TestCase.assertFalse 判断条件是否为假
TestCase.assertEquals(val1,val2) 判断val1是否和val2相等
TestCase.assertNotSame(val1,val2) 判断val1是否和val2不相等
Assert.assertArrayEquals(array1,array2) 判断两个数组相等
TestCase.fail(message) 测试直接失败,抛出message信息

注意:
assertTrue(val1 == val2) 是判断val1和val2是否是同一个实例
assertEquals(val1, val2) 是判断val1和val2值是否相等

Assert中有许多方法被淘汰了,这里建议多用TestCase

二、测试模块

  • 测试模块:我们需要写测试代码的模块
  • 驱动模块:调用我们测试代码的模块
  • 桩模块 :模拟被测试的模块所调用的模块,而不是软件产品的组成的部分,这个桩模块本身不执行任何功能仅在被调用时返回静态值来模拟被调用模块的行为

桩模块简单实例(税收计算较复杂,可以先模仿一下,作为桩模块,这样就可以不影响被测模块的测试):

三、使用Mockito作为桩模块

我们在maven中加入Mockito和junit的依赖

        <dependency><groupId>junit</groupId><artifactId>junit</artifactId><scope>test</scope></dependency><dependency><groupId>org.mockito</groupId><artifactId>mockito-core</artifactId><scope>test</scope></dependency>

数据库访问层studentDao如下(还未实现方法):

import org.springframework.stereotype.Repository;
import whu.xsy.swagger_use.entity.student;import java.util.List;@Repository
public interface studentDao {//TODO 从数据库获取所有学生信息List<student> getAll();
}

service层如下(调用studentDao):

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import whu.xsy.swagger_use.dao.studentDao;
import whu.xsy.swagger_use.entity.student;import java.util.List;@Service
public class studentService {@AutowiredstudentDao studentDao;public List<student> getAll(){return studentDao.getAll();}
}

接下来开始设置桩模块并开始测试

此时数据库并没有数据,数据访问层dao也没写好,那么该如何测试service呢?
我们使用mockito在dao层调用特定方法时模拟返回数据,这样就可以不影响service层的测试,并且即使数据库发生变化(比如环境迁移),也不影响测试。

简而言之,就是mockito接管了dao层

import junit.framework.TestCase;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import whu.xsy.swagger_use.dao.studentDao;
import whu.xsy.swagger_use.entity.student;
import whu.xsy.swagger_use.service.studentService;import java.util.ArrayList;
import java.util.List;@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
public class SwaggerUseApplicationTests {@MockBeanstudentDao studentDao;@AutowiredstudentService studentService;@Testpublic void contextLoads(){} // 可用来检测springboot环境//测试studentService@Testpublic void testStudentService(){//模拟数据库中数据List<student> students= new ArrayList<>();students.add(new student(1,"xsy"));students.add(new student(2,"theory"));//由于 studentDao 的 getAll() 方法还没写好,所以使用 Mockito 做桩模块,模拟返回数据Mockito.when(studentDao.getAll()).thenReturn( students );//调用studentService.getAll()List<student> result = studentService.getAll();//断言TestCase.assertEquals(2,result.size());TestCase.assertEquals("xsy",result.get(0).getName());}
}

四、使用mockMvc测试web层

  1. 在test类上加上 @AutoConfigureMockMvc注解
  2. 自动注入MockMvc mockMvc;
  3. 对studentController中增删改查接口进行测试
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;
import whu.xsy.swagger_use.entity.student;import java.util.ArrayList;
import java.util.List;@RestController
@RequestMapping("/student")
@Api(value = "/student", tags = "学生模块") //标注在类上的
public class studentController {//模拟数据库private static List<student> students = new ArrayList<>();//初始化模拟数据库static{students.add(new student(1,"xsy"));students.add(new student(2,"theory"));}@GetMapping("")public List<student> getAll(){return students;}@PostMapping("")public boolean add(student student){return students.add(student);}}

测试get方法(期望状态200,返回的json中含有xsy,打印返回的信息)

@SpringBootTest
@RunWith(SpringJUnit4ClassRunner.class)
@AutoConfigureMockMvc
public class SwaggerUseApplicationTests {@MockBeanstudentDao studentDao;@AutowiredstudentService studentService;@AutowiredMockMvc mockMvc;@Beforepublic void setUp() throws Exception {mockMvc = MockMvcBuilders.standaloneSetup(new studentController()).build();}@Testpublic void testStudentController() throws Exception {RequestBuilder request = null;//查询所有学生request = get("/student/");mockMvc.perform(request).andExpect(status().isOk()).andDo(MockMvcResultHandlers.print()).andExpect(content().string(Matchers.containsString("xsy")));}}

测试通过,并且打印的信息如下:

MockHttpServletRequest:HTTP Method = GETRequest URI = /student/Parameters = {}Headers = []Body = <no character encoding set>Session Attrs = {}Handler:Type = whu.xsy.swagger_use.controller.studentControllerMethod = whu.xsy.swagger_use.controller.studentController#getAll()Async:Async started = falseAsync result = nullResolved Exception:Type = nullModelAndView:View name = nullView = nullModel = nullFlashMap:Attributes = nullMockHttpServletResponse:Status = 200Error message = nullHeaders = [Content-Type:"application/json"]Content type = application/jsonBody = [{"id":1,"name":"xsy"},{"id":2,"name":"theory"}]Forwarded URL = nullRedirected URL = nullCookies = []

测试post方法:

本实例中展现了MockMvc如何上传数据和获取返回结果
测试方法与get类似

        request = post("/student/").param("id","3").param("name","ys");String result = mockMvc.perform(request).andExpect(status().isOk()).andReturn().getResponse().getContentAsString();TestCase.assertEquals("true",result);

五、批量测试和测试覆盖率

我们将service的测试和controller的测试分开:

我们需要一次性运行所有的单元测试,则需要配置一次性运行whu.xsy.swagger_use中的所有test类(具体配置见Junit自动单元测试以及测试覆盖率简单使用)


然后点击run with coverage

就可以运行所有的测试文件,并且可以看到覆盖率

springboot+junit测试相关推荐

  1. springboot junit测试时环境变量问题 idea

    背景 在写一个springboot + redis + mybatis + shiro + websocket项目时,因为曾经一不小心把密码推送到了github上因此痛定思痛把重要信息例如密码和服务器 ...

  2. SpringBoot集成JUnit测试

    在一些企业的实践中,要求开发人员编写测试编码来测试业务逻辑,以提高编码的质量.降低错误的发生概率以及进行性能测试等.这些IDE在创建Spring Boot应用的时候已经引入了测试包,只需要看到pom. ...

  3. SpringBoot整合Junit测试

    文章目录 SpringBoot整合Junit测试 1.SpringBoot引入springboot的测试依赖 2.生成测试方法 3.测试结果 SpringBoot整合Junit测试 假设已对mybat ...

  4. SpringBoot中使用Junit测试

    文章目录 SpringBoot整合Junit测试 目录 1.SpringBoot引入springboot的测试依赖 2.生成测试方法 3.测试结果 SpringBoot整合Junit测试 假设已对my ...

  5. SpringBoot系列三:SpringBoot基本概念(统一父 pom 管理、SpringBoot 代码测试、启动注解分析、配置访问路径、使用内置对象、项目打包发布)...

    声明:本文来源于MLDN培训视频的课堂笔记,写在这里只是为了方便查阅. 1.了解SpringBoot的基本概念 2.具体内容 在之前所建立的 SpringBoot 项目只是根据官方文档实现的一个基础程 ...

  6. 【sprinb-boot】Junit测试

    前言 springboot 2.0.0.RELEASE maven 3.5.0 参考:https://docs.spring.io/spring-boot/docs/2.0.0.RELEASE/ref ...

  7. java junit autowired_写Junit测试时用Autowired注入的类实例始终为空怎么解?

    踩坑半天多,终于在网上寻觅到了解决方案,特此分享一下. 重要前提:src/main/java下的根包名必须和src/test/main的根包名完全一致,否则就会发生死活不能注入的情况,要继续进行下面的 ...

  8. JUnit测试类完成后事务是默认 回滚的。只能查询数据,不能增删改。

    JUnit测试类完成后事务是默认 回滚的.只能查询数据,不能增删改. 在测试类或者测试方法上面加上注解 @Rollback(false)  表示事物不回滚,这样数据就可以提交到数据库中了. 转载于:h ...

  9. 创建JUNIT测试类

    建立JUNIT测试类步骤: 1 建立正常的JAVA工程 2  在JAVA工程的build path 的LIB中导入JUNIT4 3 工程中新建一个普通TEST.JAVA,在该类中在随便的一个方法上,反 ...

最新文章

  1. 顺序查找(c/c++)
  2. 云计算里AWS和Azure的探究(2)
  3. MATLAB 表数据结构最终篇,如何实现表操作
  4. 快讯 | 美国投资公司Avenue Capital Group联合创始人Marc Lasry:比特币价格可能达到40,000美元...
  5. C#动态生成XML并在前台用javascript读取
  6. SpringBoot 迭代输出
  7. python10086查询系统_Python获取移动性能指标
  8. java实现linux中gzip压缩解压缩算法:byte[]字节数组,文件,字符串,数据流的压缩解压缩
  9. 响应式Web设计:HTML5和CSS3实战 笔记
  10. PACPerformance
  11. python制作动态表情包,用 Python 开发一个【GIF表情包制作神器】
  12. 记公司同事的一次集体活动
  13. 微信公众平台测试号推送思路
  14. 交换机vlan配置实训心得_交换机与VLAN的配置实验报告.doc
  15. ES安装报错信息(持续更新)
  16. SQL SERVER 为现有表中增加列
  17. HDU 2340 Obfuscation(dp)
  18. 核酸检测软件开发方案(软件工程作业)
  19. 2021年制冷与空调设备安装修理复审考试及制冷与空调设备安装修理作业考试题库
  20. 中国移动增值服务的现状及趋势

热门文章

  1. 编程语言python入门-手把手教你从零开始用Python语言写爬虫程序
  2. 1000行代码入门python-Python基础知识和工作环境
  3. 学python需要什么基础-学Python需要什么基础知识?零基础可以学Python吗?
  4. 盘点语音识别技术在人工智能中的应用
  5. centos dns服务器_用 OpenStack Designate 构建一个 DNS 即服务(DNSaaS) | Linux 中国
  6. b5对战一直检索服务器信息,【B5平台】求解封,服务器问题啊
  7. 搭建NodeJS环境
  8. 视频质量,分辨率以及码率之间的关系
  9. 超边际分析不能用计算机,一种基于超边际分析的分布式计算资源分配方法-Journalof.PDF...
  10. POI设置单元格格式