Junit5单元测试的常用注解

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 :为测试类或测试方法提供扩展类引用
import org.junit.jupiter.api.Test; //注意这里使用的是jupiter的Test注解!!

@DisplayName("Junit5功能测试类")
@SpringBootTest
class SpringMvdApplicationTests {

    @Autowired
    RedisTemplate redisTemplate;

    @DisplayName("测试displayName注解")
    @Test
    void testRedis() {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set("hello", "world");
        System.out.println(operations.get("hello"));
    }

    @DisplayName("测试displayName注解")
    @Test
    void tes1() {
        System.out.println("test.....");
    }

    @DisplayName("测试displayName注解")
    @Disabled //表示忽略不生效
    @Test
    void tes2() {
        System.out.println("test.....");
    }

    //超时就报错
    @Timeout(value = 500, unit = TimeUnit.MILLISECONDS)
    @Test
    void testTimeOut() throws InterruptedException {
        Thread.sleep(600);
    }

    @BeforeEach
    void testBefore() {
        System.out.println("在每一个测试开始之前执行");
    }

    @AfterEach
    void testAfter() {
        System.out.println("在每个test之后执行");
    }

    @BeforeAll
    static void testBeforeAll() {
        System.out.println("在所有test之前执行");
    }

    @AfterAll
    static void testAfterAll() {
        System.out.println("在所test之后执行");
    }
}
上一篇:如何使用Junit 5在Spring Boot 2.1.0.M4中使用@DataJpaTest测试Spring CrudRepository


下一篇:java-junit5-并行运行测试(在pom中没有forkCount)