五、springboot单元测试
1.为什么要写测试用例
1. 可以避免测试点的遗漏,为了更好的进行测试,可以提高测试效率
2. 可以自动测试,可以在项目打包前进行测试校验
3. 可以及时发现因为修改代码导致新的问题的出现,并及时解决
2.Junit基本注解介绍
//在所有测试方法前执行一次,一般在其中写上整体初始化的代码
@BeforeClass
//在所有测试方法后执行一次,一般在其中写上销毁和释放资源的代码
@AfterClass
//在每个测试方法前执行,一般用来初始化方法(比如我们在测试别的方法时,类中与其他测试方法共享的值已经被改变,为了保证测试结果的有效性,我们会在@Before注解的方法中重置数据)
@Before
//在每个测试方法后执行,在方法执行完成后要做的事情
@After
// 测试方法执行超过1000毫秒后算超时,测试将失败
@Test(timeout = 1000)
// 测试方法期望得到的异常类,如果方法执行没有抛出指定的异常,则测试失败
@Test(expected = Exception.class)
// 执行测试时将忽略掉此方法,如果用于修饰类,则忽略整个类
@Ignore(“not ready yet”)
@Test
@RunWith
在JUnit中有很多个Runner,他们负责调用你的测试代码,每一个Runner都有各自的特殊功能,你要根据需要选择不同的Runner来运行你的测试代码。
如果我们只是简单的做普通Java测试,不涉及Spring Web项目,你可以省略@RunWith注解,这样系统会自动使用默认Runner来运行你的代码。
3.单元测试
1、在pom包中添加spring-boot-starter-test包引用
spring-boot-starter-test :测试模块,包括JUnit、Hamcrest、Mockito
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2、开发测试类
以最简单的helloworld为例,在测试类的类头部需要添加:@RunWith(SpringRunner.class)和@SpringBootTest注解,在测试方法的顶端添加@Test即可,最后在方法上点击右键run就可以运行。
@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests { @Test
public void hello() {
System.out.println("hello world");
} }
实际使用中,可以按照项目的正常使用去注入dao层代码或者是service层代码进行测试验证,spring-boot-starter-test提供很多基础用法,更难得的是增加了对Controller层测试的支持。
//简单验证结果集是否正确
Assert.assertEquals(3, userMapper.getAll().size()); //验证结果集,提示
Assert.assertTrue("错误,正确的返回值为200", status == 200);
Assert.assertFalse("错误,正确的返回值为200", status != 200);
引入了MockMvc支持了对Controller层的测试,简单示例如下:
public class HelloControlerTests {
private MockMvc mvc;
//初始化执行
@Before
public void setUp() throws Exception {
mvc = MockMvcBuilders.standaloneSetup(new HelloController()).build();
}
//验证controller是否正常响应并打印返回结果
@Test
public void getHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(MockMvcResultMatchers.status().isOk())
.andDo(MockMvcResultHandlers.print())
.andReturn();
}
//验证controller是否正常响应并判断返回结果是否正确
@Test
public void testHello() throws Exception {
mvc.perform(MockMvcRequestBuilders.get("/hello").accept(MediaType.APPLICATION_JSON))
.andExpect(status().isOk())
.andExpect(content().string(equalTo("Hello World")));
}
}
4.SpringBoot Web项目中中如何使用Junit
@RunWith(SpringJUnit4ClassRunner.class) // SpringJUnit支持,由此引入Spring-Test框架支持!
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class) // 指定我们SpringBoot工程的Application启动类
@WebAppConfiguration // 由于是Web项目,Junit需要模拟ServletContext,因此我们需要给我们的测试类加上@WebAppConfiguration。
测试方法使用@Test注解标注即可
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
@WebAppConfiguration
public class StudentTest { @Autowired
private StudentService studentService; @Test
public void likeName() {
assertArrayEquals(
new Object[]{
studentService.likeName("小明2").size() > 0,
studentService.likeName("坏").size() > 0,
studentService.likeName("莉莉").size() > 0
},
new Object[]{
true,
false,
true
}
);
// assertTrue(studentService.likeName("小明2").size() > 0);
} }
https://www.cnblogs.com/cx987514451/p/9304525.html
https://www.cnblogs.com/shunyang/p/8681111.html
https://www.cnblogs.com/aston/p/7259825.html
5.使用Junit测试HTTP的API接口
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
//@WebAppConfiguration // 使用@WebIntegrationTest注解需要将@WebAppConfiguration注释掉
@WebIntegrationTest("server.port:0")// 使用0表示端口号随机,也可以具体指定如8888这样的固定端口
public class HelloControllerTest { private String dateReg;
private Pattern pattern;
private RestTemplate template = new TestRestTemplate();
@Value("${local.server.port}")// 注入端口号
private int port; @Test
public void test3(){
String url = "http://localhost:"+port+"/myspringboot/hello/info";
MultiValueMap<String, Object> map = new LinkedMultiValueMap<String, Object>();
map.add("name", "Tom");
map.add("name1", "Lily");
String result = template.postForObject(url, map, String.class);
System.out.println(result);
assertNotNull(result);
assertThat(result, Matchers.containsString("Tom"));
} }
6.捕获输出
@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = SpringBootSampleApplication.class)
//@WebAppConfiguration // 使用@WebIntegrationTest注解需要将@WebAppConfiguration注释掉
@WebIntegrationTest("server.port:0")// 使用0表示端口号随机,也可以具体指定如8888这样的固定端口
public class HelloControllerTest { @Value("${local.server.port}")// 注入端口号
private int port; private static final Logger logger = LoggerFactory.getLogger(StudentController.class); @Rule
// 这里注意,使用@Rule注解必须要用public
public OutputCapture capture = new OutputCapture(); @Test
public void test4(){
System.out.println("HelloWorld");
logger.info("logo日志也会被capture捕获测试输出");
assertThat(capture.toString(), Matchers.containsString("World"));
}
}
7.打包测试
打包测试,就是新增一个类,然后将我们写好的其他测试类配置在一起,然后直接运行这个类就达到同时运行其他几个测试的目的。
@RunWith(Suite.class)
@SuiteClasses({ATest.class, BTest.class, CTest.class})
public class ABCSuite {
// 类中不需要编写代码
}
参考:
http://www.ityouknow.com/springboot/2017/05/09/springboot-deploy.html
https://blog.csdn.net/catoop/article/details/50752964
五、springboot单元测试的更多相关文章
- Springboot单元测试Junit深度实践
Springboot单元测试Junit深度实践 前言 单元测试的好处估计大家也都知道了,但是大家可以发现在国内IT公司中真正推行单测的很少很少,一些大厂大部分也只是在核心产品推广单测来保障质量,今天这 ...
- springmvc,springboot单元测试配置
1. springmvc单元测试配置 <dependency> <groupId>junit</groupId> <artifactId>junit&l ...
- springboot系列三、springboot 单元测试、配置访问路径、多个配置文件和多环境配置,项目打包发布
一.单元测试 生成的demo里面包含spring-boot-starter-test :测试模块,包括JUnit.Hamcrest.Mockito,没有的手动加上. <dependency> ...
- SpringBoot单元测试中的事务和Session
1.Springboot中使用junit编写单元测试,并且测试结果不影响数据库. 2.
- SpringBoot单元测试
一.Service层Junit单元测试 需要的jar包 <dependency> <groupId>org.springframework.boot</groupId&g ...
- springboot(十二):springboot单元测试、打包部署
单元测试 1.在pom包中添加spring-boot-starter-test包引用 <dependency> <groupId>org.springframework.boo ...
- Springboot单元测试(MockBean||SpyBean)
转载:https://blog.csdn.net/maiyikai/article/details/78483423 本来要写springboot集成netty实现的,但是想起来单元测试没总结,那就趁 ...
- springBoot单元测试-基础单元测试
1)在pom文件中加入junit支持 <!-- spring-boot-starter-test 单元测试 --> <dependency> <groupId>or ...
- 【使用篇二】SpringBoot单元测试(10)
SpringCloud单元测试:https://www.cnblogs.com/myitnews/p/11796321.html 1. 创建项目Maven Project,修改pom.xml < ...
随机推荐
- 【刷题】洛谷 P3872 [TJOI2010]电影迷
题目描述 小A是一个电影迷,他收集了上百部的电影,打算从中挑出若干部在假期看完.他根据自己的口味和网上的介绍,对每部电影X都打了一个分数vX,表示自己喜欢的程度.这个分数的范围在-1000至1000之 ...
- IoT与区块链的机遇与挑战
区块链, 分布式账本技术的一种形式, 自从2014年或多或少地获得了大量的关注: 区块链和物联网, 区块链和安全, 区块链和金融, 区块链和物流, 凡是你能想到的,仿佛都可以应用区块链. 在本文中, ...
- 洛谷 P1053 逛公园 解题报告
P3953 逛公园 问题描述 策策同学特别喜欢逛公园. 公园可以看成一张\(N\)个点\(M\)条边构成的有向图,且没有自环和重边.其中1号点是公园的入口,\(N\)号点是公园的出口,每条边有一个非负 ...
- linux内核设计与实现一书阅读整理 之第十八章
CHAPTER 18 调试 18.1 准备开始 需要的是准备是: - 一个bug - 一个藏匿bug的内核版本 - 相关内核代码的知识和运气 重点: 想要成功的进行调试,就取决于是否能让这些错误重现. ...
- java多线程 -- ForkJoinPool 分支/ 合并框架 工作窃取
Fork/Join 框架:就是在必要的情况下,将一个大任务,进行拆分(fork)成若干个小任务(拆到不可再拆时),再将一个个的小任务运算的结果进行 join 汇总. Fork/Join 框架与线程池的 ...
- BZOJ 3098 Hash Killer II
3098: Hash Killer II Description 这天天气不错,hzhwcmhf神犇给VFleaKing出了一道题: 给你一个长度为N的字符串S,求有多少个不同的长度为L的子串. 子串 ...
- 【树状数组】【P4113】[HEOI2012]采花
Description 给定一个长度为 \(n\) 的序列,有 \(m\) 次询问,每次询问一段区间,求区间中有多少个数出现次数超过 \(1\) 次 Limitation \(n,~m~\leq~2~ ...
- python之旅:面向对象之继承与派生
一 初识继承 编写类时,并非总要从空白开始.如果你要编写的类正好是另一个现成类的特殊版本,可使用继承来减少代码冗余,子类会“遗传”父类的属性,从而解决代码重用问题 什么是继承 继承是一种创建新类的方式 ...
- configServer的高可用
1.利用RabbitMQ或者是Kafka来搭建集群. 2.利用nginx来进行 3.利用Eureka来搭建
- Centos6.6系统root用户密码恢复案例
1.重新启动主机后,在出现Grub菜单时按上下键取消倒计时 2.进入到内核引导界面按e键如下所示: 3.将鼠标定位到Kernel这一行按e键 4.在行尾输入”single”也可以换成字母”s”或者数字 ...