本次介绍如何在Springboot中编写测试类。
不使用spring bean时的测试用例代码编写步骤:
1、在pom.xml中加上junit依赖2、在项目的test/java目录下创建测试类文件junit junit 4.12
注意类的修饰符是public,不然单元测试无法使用。
方法的修饰符也是public,同时返回设置为void。在方法上加上@Test注解,注意是org.junit包下的。
相关注解:
| 注解 | 作用 |
|---|---|
| @Test(excepted==xx.class,timeout=毫秒数) | 修饰一个方法为测试方法,excepted参数可以忽略某些异常类 |
| @Before | 在每一个测试方法被运行前执行一次 |
| @BeforeClass | 在所有测试方法执行前执行 |
| @After | 在每一个测试方法运行后执行一次 |
| @AfterClass | 在所有测试方法执行后执行 |
| @Ignore | 修饰的类或方法会被测试运行器忽略 |
| @RunWith | 更改测试运行器 |
2、在项目的test/java目录下创建测试类文件org.springframework.boot spring-boot-starter-test test
类的定义类似不使用spring bean时的格式。但注意在类名上加上springboot test注解:
@SpringBootTest(classes = TestMain.class) @RunWith(SpringRunner.class)
TestMain是项目启动类。
3、在类中编写测试方法格式跟不使用spring bean时的类似。
4、其他:制定配置文件方法
@TestPropertySource
properties属性
例如:
@TestPropertySource(properties = {“spring.config.location = classpath:bootstrap-test.yml”})
参考文档:
https://www.cnblogs.com/fnlingnzb-learner/p/12068505.html



