一.前言
1.介绍
- 编写单元测试可以帮助开发人员编写高质量的代码,提升代码质量,减少Bug,便于重构。
spring-boot-starter-test
也秉承了开箱即用的原则,集成了许多优秀的类库,可以很方便的帮助我们进行测试使用- spring-boot测试的核心包,一个为
spring-boot-test
包含核心项,另一个为spring-boot-test-autoconfigure
支持了测试的自动配置
2.集成类库
-
JUnit 4:Java应用程序标注的单元测试
-
Spring Test & Spring Boot Test:对spring boot程序单元测试和集成测试提供支持
-
AssertJ:一个流畅的断言库,提供返回值的测试比较
-
Hamcrest:匹配器对象库(也称为约束或谓词)
-
Mockito:一个Java 模拟框架,用于模拟请求,java bean等
-
JSONassert:对JSON对象或者JSON字符串断言的库
-
JsonPath,提供类似XPath那样的符号来获取JSON数据片段
可见依赖列表:
3.官方文档
- spring-boot-testing介绍
- junit注解
- spring-framework中test介绍
- 其中spring-boot的官网文档介绍都是一些集成使用,spring-framework中test模块介绍了详细用法,有时需要了解spring-boot集成的每个模块功能的细节,可以浏览此地址下超链接
JUnit 4
,Spring Test & Spring Boot Test
,AssertJ
,Hamcrest
,Mockito
,JSONassert
,JsonPath
4.项目例子
- spring-boot项目地址完整例子传送门
- spring-cloud项目地址完整例子传送门
- 此篇文章用到项目模块:
二.Spring Boot Test
1.基本样式
- spring boot的测试类,基本接口如下
1.@RunWith(SpringRunner.class) @SpringBootTest public class TestingApplicationTests { @Test public void contextLoads() { } }
@RunWith(SpringRunner.class)
:@RunWith
是一个JUnit4的注解,表明测试运行器,SpringRunner.class
表明获取spring上下文支持;如果使用JUnit5可以不用添加此注解,因为@SpringBootTest
中集成了@RunWith
2.@SpringBootTest
:加载Web ApplicationContext
并提供模拟Web环境,其的搜索算法从包含测试包开始工作,直到找到用@SpringBootApplicationor
或者@SpringBootConfiguration
注释的类
2.Junit注解
- Junit在spring boot test 中大量使用,下面介绍了Junit包含的注解和用法
- JUnit注解中包含了几个比较重要的注解:
@BeforeClass
、@AfterClass
、@Before
、@After
、@Test
、@Ignore
。其中,@BeforeClass
和@AfterClass
在测试类加载的开始和结束时运行,必须为静态方法;而@Before
和@After
则在每个测试方法开始之前和结束之后运行。@Ignore
忽略的测试方法(只在测试类的时候生效,单独执行该测试方法无效),见如下例子:@RunWith(SpringRunner.class) @SpringBootTest public class TestingApplicationTests { @Test @Ignore public void contextLoads() { } @BeforeClass public static void beforeClassTest() { System.out.println("before class test"); } @Before public void beforeTest() { System.out.println("before test"); } @Test public void Test1() { System.out.println("test 1*1=1"); Assert.assertEquals(1, 1 * 1);