依赖
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency>
1.注解列表
- @RunWith:标识为JUnit的运行环境;
- @SpringBootTest:获取启动类、加载配置,确定装载Spring Boot;
- @Test:声明需要测试的方法;
- @BeforeClass:针对所有测试,只执行一次,且必须为static void;
- @AfterClass:针对所有测试,只执行一次,且必须为static void;
- @Before:每个测试方法前都会执行的方法;
- @After:每个测试方法前都会执行的方法;
- @Ignore:忽略方法;
@RunWith(SpringRunner.class) @SpringBootTest(classes = {Application.class}, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) //不必显示指明启动类等 @ActiveProfiles("xx") @Transactional @Slf4j // 日志
创建测试类方法:https://www.w3cschool.cn/intellij_idea_doc/intellij_idea_doc-mrn42f9j.html
右键 >>>GO TO >>> TEST
2.Assert断言
- Assert.assertEquals 对比两个值相等
- Assert.assertNotEquals 对比两个值不相等
- Assert.assertSame 对比两个对象的引用相等
- Assert.assertArrayEquals 对比两个数组相等
- Assert.assertTrue 验证返回是否为真
- Assert.assertFlase 验证返回是否为假
- Assert.assertNull 验证null
- Assert.assertNotNull 验证非null
3.Web模拟测试
@RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) public class TestServiceImplTest { @Autowired private TestRestTemplate restTemplate; @DisplayName("接口描述,展示测试方法") @Test public void test() { restTemplate.getForObject(xx, xx) } }
4.数据库测试
给测试类上添加“@Transactional”,这样既可以测试数据操作方法,又不会污染数据库了。
junit5测试:Java单元测试之JUnit 5快速上手
https://www.cnblogs.com/vipstone/p/9908545.html
JUnit基本注解使用
https://www.jianshu.com/p/921282034c5d
https://blog.csdn.net/qq_42651904/article/details/89945495
5.cron表达式
* 第一位,表示秒,取值0-59
* 第二位,表示分,取值0-59
* 第三位,表示小时,取值0-23
* 第四位,日期天/日,取值1-31
* 第五位,日期月份,取值1-12
* 第六位,星期,取值1-7,星期一,星期二...,注:不是第1周,第二周的意思
另外:1表示星期天,2表示星期一。
* 第7为,年份,可以留空,取值1970-2099
(*)星号:可以理解为每的意思,每秒,每分,每天,每月,每年...
(?)问号:问号只能出现在日期和星期这两个位置。
(-)减号:表达一个范围,如在小时字段中使用“10-12”,则表示从10到12点,即10,11,12
(,)逗号:表达一个列表值,如在星期字段中使用“1,2,4”,则表示星期一,星期二,星期四
(/)斜杠:如:x/y,x是开始值,y是步长,比如在第一位(秒) 0/15就是,从0秒开始,每15秒,最后就是0,15,30,45,60 另:*/y,等同于0/y