JUnit 5 @BeforeEach注解详解

后端 潘老师 6个月前 (10-23) 129 ℃ (0) 扫码查看

在JUnit 5中,@BeforeEach注解被用于表示当前类中的@Test、@RepeatedTest、@ParameterizedTest或@TestFactory方法每次调用之前都应执行被注解的方法。@BeforeEach注解是JUnit 5中的测试生命周期方法之

一,用于替换JUnit 4中的@Before注解。默认情况下,测试方法将与@BeforeEach注解的方法在同一个线程中执行。

1.@BeforeEach的使用方法

1)在方法上添加@BeforeEach注解,如下所示:

@BeforeEach
public void initEach(){
     //test setup code
}

@Test
void succeedingTest() {
    //test code and assertions
}

2)@BeforeEach带注释的方法不能是静态方法,否则会抛出运行时错误。

@BeforeEach
public static void initEach(){
     //test setup code
}

//Error


org.junit.platform.commons.JUnitException: @BeforeEach method 'public static void com.howtodoinjava.junit5.examples. JUnit5AnnotationsExample.initEach()' must not be static.
at org.junit.jupiter.engine.descriptor. LifecycleMethodUtils.assertNonStatic(LifecycleMethodUtils.java:73)

需要注意的是,如果父类(或接口)中存在@BeforeEach注解的方法,它将被子类继承,只要该方法没有被隐藏或覆盖。另外,父类(或接口)中的@BeforeEach注解的方法将在子类中的方法之前执行。

2.@BeforeEach示例

我们将使用Calculator类并添加一个add()方法进行测试。我们将使用@RepeatedTest注解测试该方法5次,这将导致add()测试方法运行5次。@BeforeEach带注释的方法应该在每次调用测试方法时执行。

public class BeforeEachTest {

    @DisplayName("Add operation test")
    @RepeatedTest(5)
    void addNumber(TestInfo testInfo, RepetitionInfo repetitionInfo) {

        System.out.println("Running test -> " + repetitionInfo.getCurrentRepetition());
        Assertions.assertEquals(2, Calculator.add(1, 1), "1 + 1 should equal 2");
    }

    @BeforeAll
    public static void init(){
        System.out.println("BeforeAll init() method called");
    }

    @BeforeEach
    public void initEach(){
        System.out.println("BeforeEach initEach() method called");
    }
}

其中Calculator类如下所示:

public class Calculator
{
    public int add(int a, int b) {
        return a + b;
    }
}

现在执行测试,您将看到以下控制台输出:

BeforeAll init() method called
BeforeEach initEach() method called

BeforeEach initEach() method called
Running test -> 1

BeforeEach initEach() method called
Running test -> 2

BeforeEach initEach() method called
Running test -> 3

BeforeEach initEach() method called
Running test -> 4

BeforeEach initEach() method called
Running test -> 5

显然,@BeforeEach注解的initEach()方法每次测试方法调用时都会被调用一次。


版权声明:本站文章,如无说明,均为本站原创,转载请注明文章来源。如有侵权,请联系博主删除。
本文链接:https://www.panziye.com/back/10272.html
喜欢 (0)
请潘老师喝杯Coffee吧!】
分享 (0)
用户头像
发表我的评论
取消评论
表情 贴图 签到 代码

Hi,您需要填写昵称和邮箱!

  • 昵称【必填】
  • 邮箱【必填】
  • 网址【可选】