JUnit5的注解与JUnit4的注解有所变化
https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations
- @Test :表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一不能声明任何属性,拓展的测试将会由Jupiter提供额外测试
- @ParameterizedTest :表示方法是参数化测试,下方会有详细介绍
- @RepeatedTest :表示方法可重复执行,下方会有详细介绍
- @DisplayName :为测试类或者测试方法设置展示名称
- @BeforeEach :表示在每个单元测试之前执行
- @AfterEach :表示在每个单元测试之后执行
- @BeforeAll :表示在所有单元测试之前执行
- @AfterAll :表示在所有单元测试之后执行
- @Tag :表示单元测试类别,类似于JUnit4中的@Categories
- @Disabled :表示测试类或测试方法不执行,类似于JUnit4中的@Ignore
- @Timeout :表示测试方法运行如果超过了指定时间将会返回错误
- @ExtendWith :为测试类或测试方法提供扩展类引用
package com.example.demo;
import com.example.demo.bean.User;
import com.example.demo.mapper.UserMapper;
import org.junit.jupiter.api.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import java.util.concurrent.TimeUnit;
@SpringBootTest //可以使用容器中的内容
class MysqlTestApplicationTests {
@Autowired
UserMapper userMapper;
@RepeatedTest(5) //重复测试五次
@Disabled //禁用该测试
@Timeout(value = 5, unit = TimeUnit.SECONDS) //超过5s 就是超时
@DisplayName("usermapper test") //该测试的名称
@Test
void testUserMapper(){
User user = userMapper.selectById(1L);
System.out.println(user.toString());
}
@Autowired
StringRedisTemplate stringRedisTemplate;
@DisplayName("redis test")
@Test
void testRedis(){
stringRedisTemplate.opsForValue().set("aaa","1");
System.out.println(stringRedisTemplate.opsForValue().get("aaa"));
}
//在每个测试开始前
@BeforeEach
void testBeforEach(){
System.out.println("start test");
}
//在每个测试开始后
@AfterEach
void testAfterEach(){
System.out.println("end test");
}
//在所有测试开始之前执行 用于开启某些连接
@BeforeAll
static void testBeforAll(){
System.out.println("start all test");
}
//在所有测试开始之后 用于关闭某些连接
@AfterAll
static void testAfterAll(){
System.out.println("after all test");
}
}