目录
2.2.2、@DisplayName :为测试类或者测试方法设置展示名称
2.2.3、@BeforeEach、@AfterEach、@BeforeAll、@AfterAll
2.2.4、@Disabled :表示测试类或测试方法不执行
2.2.5、@Timeout :表示测试方法运行如果超过了指定时间将会返回错误
2.2.6、@RepeatedTest :表示方法可重复执行
1、JUnit5概述
1.1、JUnit5 构成
JUnit5 由三个不同子项目的几个不同模块组成。
JUnit 5 = JUnit Platform + JUnit Jupiter + JUnit Vintage
1)JUnit Platform: 是在JVM上启动测试框架的基础,不仅支持Junit自制的测试引擎,其他测试引擎也都可以接入。
2)JUnit Jupiter: 提供了JUnit5的新的编程模型,是JUnit5新特性的核心。内部包含了一个测试引擎,用于在Junit Platform上运行。
3)JUnit Vintage: 由于JUint已经发展多年,为了照顾老的项目,其提供了兼容JUnit4.x,Junit3.x的测试引擎。
1.2、JUnit5 配置
1.2.1、导入 Junit5 开发场景
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
1.2.2、Junit5 开发场景自动导入依赖项
2、JUnit5 使用
2.1、Jnuit5 测试代码开发
2.1.1、测试代码格式
@SpringBootTest注解:添加在需要依赖springboot框架的测试类上,
不然不能使用Springboot的相关开发功能
@Test注解:添加在测试方法上
@SpringBootTest
class Boot05WebAdminApplicationTests {
@Test
void contextLoads() {
}
}
2.1.2、测试样例
@Slf4j
@SpringBootTest
class SpringBootThymeleafApplicationTests {
@Autowired
JdbcTemplate jdbcTemplate;
@Autowired
DataSource dataSource;
@Autowired
UserMapper userMapper;
@Autowired
StringRedisTemplate redisTemplate;
@Test
void contextLoads() {
Long along = jdbcTemplate.queryForObject("select count(*) from account", long.class);
log.info("记录总数{}", along);
log.info("数据源类型{}", dataSource.getClass());
}
@Test
void testUserMapper() {
User user = userMapper.selectById(1);
log.info("用户信息{}", user);
}
@Test
void testRedis() {
ValueOperations<String, String> operations = redisTemplate.opsForValue();
operations.set("hello", "world");
String hello = operations.get("hello");
System.out.println(hello);
}
}
2.2、JUnit5常用注解
2.2.1、@Test :表示方法是测试方法。
@SpringBootTest
class Boot05WebAdminApplicationTests {
@Test
void contextLoads() {
}
}
2.2.2、@DisplayName :为测试类或者测试方法设置展示名称
测试代码:
@DisplayName("junit5功能测试")
public class Junit5Test {
@DisplayName("测试displayname注解")
@Test
void testDisplayName() {
System.out.println(1);
}
}
输出结果:
2.2.3、@BeforeEach、@AfterEach、@BeforeAll、@AfterAll
注解功能:
注解 | 功能 |
@BeforeEach |
表示在每个单元测试之前执行 |
@AfterEach |
表示在每个单元测试之后执行 |
@BeforeAll |
表示在所有单元测试之前执行 |