Contents

在非静态方法中使用@BeforeAll和@AfterAll

1. 概述

在这个简短的教程中,我们将使用*Junit5 中可用的@BeforeAll@AfterAll*注解来实现非静态方法。

2.非静态方法中的*@BeforeAll@AfterAll*

在进行单元测试时,我们可能偶尔希望在非静态设置和拆卸方法中使用*@BeforeAll@AfterAll*——例如,在*@Nested*测试类中或作为接口默认方法。

让我们使用*@BeforeAll@AfterAll*方法作为非静态方法创建一个测试类:

public class BeforeAndAfterAnnotationsUnitTest {
    String input;
    Long result;
    @BeforeAll
    public void setup() {
        input = "77";
    }
    @AfterAll
    public void teardown() {
        input = null;
        result = null;
    }
    @Test
    public void whenConvertStringToLong_thenResultShouldBeLong() {
        result = Long.valueOf(input);
        Assertions.assertEquals(77l, result);
    }
}

如果我们运行上面的代码,它会抛出一个异常:

org.junit.platform.commons.JUnitException:  ...

现在让我们看看如何避免这种情况。

3. @TestInstance注解

我们将使用@TestInstance 注解来配置测试的生命周期。如果我们不在我们的测试类中声明它,生命周期模式将默认为PER_METHOD。因此,*为了防止我们的测试类抛出*JUnitException,我们需要使用@TestInstance(TestInstance.Lifecycle.PER_CLASS)对其进行注解。

让我们重做我们的测试类并添加*@TestInstance(TestInstance.Lifecycle.PER_CLASS)*:

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
public class BeforeAndAfterAnnotationsUnitTest {
    String input;
    Long result;
    @BeforeAll
    public void setup() {
        input = "77";
    }
    @AfterAll
    public void teardown() {
        input = null;
        result = null;
    }
    @Test
    public void whenConvertStringToLong_thenResultShouldBeLong() {
        result = Long.valueOf(input);
        Assertions.assertEquals(77l, result);
    }
}

在这种情况下,我们的测试运行成功。