在 JUnit5 中,测试生命周期由 4 个主要注解驱动,即@BeforeAll@BeforeEach@AfterEach@AfterAll。与此同时,每个测试方法都必须标注@Test注解。

生命周期结构

http://junit.org/junit5/docs/current/user-guide/images/extensions_lifecycle.png

Before & After

在 junit 测试生命周期中,我们需要一些方法来设置和清除测试运行的环境或测试数据。

在 JUnit 中,对于每个测试 - 创建了一个新的测试实例。@BeforeAll和 @AfterAll注释 - 以其名称清除 - 在整个测试执行周期中只应调用一次。所以他们必须被宣布

在 JUnit 中,对于每个测试 ,都会创建了一个新的测试实例。@BeforeAll@AfterAll注解,在整个测试执行周期中只应调用一次。所以他们必须被声明为static

如果他们是用相同注释注释的多个方法(例如两个方法@BeforeAll),那么它们的执行顺序是不确定的。

@BeforeEach@AfterEach为每个测试实例调用,所以他们不需要static

public class AppTest {

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

    @BeforeEach
    void setupThis(){
        System.out.println("@BeforeEach executed");
    }

    @Test
    void testCalcOne()
    {
        System.out.println("======TEST ONE EXECUTED=======");
        Assertions.assertEquals( 4 , Calculator.add(2, 2));
    }

    @Test
    void testCalcTwo()
    {
        System.out.println("======TEST TWO EXECUTED=======");
        Assertions.assertEquals( 6 , Calculator.add(2, 4));
    }

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

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

控制台输出

@BeforeAll executed

@BeforeEach executed
======TEST ONE EXECUTED=======
@AfterEach executed

@BeforeEach executed
======TEST TWO EXECUTED=======
@AfterEach executed

@AfterAll executed

禁用测试

要在 JUnit 5 中禁用测试,您将需要使用@Disabled注释。它相当于 JUnit 4 的@Ignored注释。

@Disabled 注释可以应用于测试类(禁用该类中的所有测试方法)或单独的测试方法。

@Disabled
@Test
void testCalcTwo()
{
    System.out.println("======TEST TWO EXECUTED=======");
    Assertions.assertEquals( 6 , Calculator.add(2, 4));
}

断言

在任何测试方法中,ou 将需要确定它是否通过失败。你可以使用断言来做。资产有助于通过测试用例的实际输出验证预期输出。为了保持简单,所有 JUnit Jupiter 断言是 org.junit.jupiter.Assertions 类中的静态方法。

void testCase()
{
    //Test will pass
    Assertions.assertEquals(4, Calculator.add(2, 2));

    //Test will fail
    Assertions.assertEquals(3, Calculator.add(2, 2), "Calculator.add(2, 2) test failed");

    //Test will fail
    Supplier<String> messageSupplier  = ()-> "Calculator.add(2, 2) test failed";
    Assertions.assertEquals(3, Calculator.add(2, 2), messageSupplier);
}