SpringBoot2.4:JUnit5单元测试常用注解

JUnit5

SpringBoot 2.4 以上版本移除了默认对 Vintage 的依赖。如果需要兼容junit4需要自行引入(不能使用junit4的功能 @Test)

JUnit 5’s Vintage Engine Removed from spring-boot-starter-test,如果需要继续兼容junit4需要自行引入vintage

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>org.hamcrest</groupId>
            <artifactId>hamcrest-core</artifactId>
        </exclusion>
    </exclusions>
</dependency>

junit5:https://junit.org/junit5/docs/current/user-guide/#writing-tests-annotations

JUnit5常用注解:

@Test :表示方法是测试方法。但是与JUnit4的@Test不同,他的职责非常单一不能声明任何属性,拓展的测试将会由Jupiter提供额外测试

@ParameterizedTest :表示方法是参数化测试,下方会有详细介绍

@RepeatedTest :表示方法可重复执行,下方会有详细介绍

@DisplayName :为测试类或者测试方法设置展示名称

@BeforeEach :表示在每个单元测试之前执行

@AfterEach :表示在每个单元测试之后执行

@BeforeAll :表示在所有单元测试之前执行

@AfterAll :表示在所有单元测试之后执行

@Tag :表示单元测试类别,类似于JUnit4中的@Categories

@Disabled :表示测试类或测试方法不执行,类似于JUnit4中的@Ignore

@Timeout :表示测试方法运行如果超过了指定时间将会返回错误

@ExtendWith :为测试类或测试方法提供扩展类引用

演示@DisplayName:

@Test
@DisplayName("test1方法")
public void test1(){
    System.out.println("test1");
}

image-20210402161119577

演示@BeforeEach和@AfterEach

    @BeforeEach
    void befor(){
        System.out.println("before");
    }
    @AfterEach
    void after(){
        System.out.println("after");
    }

image-20210402161234349

演示@BeforeAll和@AfterAll

@DisplayName("JUnit5Test测试类")
public class JUnit5Test {

    @BeforeEach
    void befor(){
        System.out.println("before");
    }

    @Test
    @DisplayName("test1方法")
    public void test1(){
        System.out.println("test1");
    }

    @Test
    @DisplayName("test2方法")
    public void test2(){
        System.out.println("test2");
    }

    @AfterEach
    void after(){
        System.out.println("after");
    }

    @AfterAll
    static void afterAll(){
        System.out.println("afterAll");
    }

    @BeforeAll
    static void beforeAll(){
        System.out.println("beforeAll");
    }
}

运行这个类:

image-20210402161530867

image-20210402161603216

演示@Disabled

在test2方法上加上@Disabled注解,然后执行整个测试类

image-20210402161830040

演示:@Timeout

    @Test
    @Timeout(value = 3)//默认单位为秒
    @DisplayName("测试超时")
    void testTime() throws InterruptedException {
        TimeUnit.SECONDS.sleep(5);
    }
image-20210402162035065

演示:@RepeatedTest

    @Test
    @RepeatedTest(3)
    @DisplayName("test1方法")
    public void test1(){
        System.out.println("test1");
    }

image-20210402163131469

原文地址:https://www.cnblogs.com/wwjj4811/p/14611342.html