Java @Before、@BeforeClass、@BeforeEach 和 @BeforeAll 之间的区别

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20295578/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:54:58  来源:igfitidea点击:

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

javajunitannotationsjunit4junit5

提问by user1170330

What is the main difference between

之间的主要区别是什么

  • @Beforeand @BeforeClass
    • and in JUnit 5 @BeforeEachand @BeforeAll
  • @Afterand @AfterClass
  • @Before@BeforeClass
    • 在 JUnit 5@BeforeEach@BeforeAll
  • @After@AfterClass

According to the JUnit Api@Beforeis used in the following case:

根据JUnit Api@Before在以下情况下使用:

When writing tests, it is common to find that several tests need similar objects created before they can run.

在编写测试时,通常会发现多个测试需要创建类似的对象才能运行。

Whereas @BeforeClasscan be used to establish a database connection. But couldn't @Beforedo the same?

@BeforeClass可用于建立数据库连接。但不能@Before这样做吗?

采纳答案by dasblinkenlight

The code marked @Beforeis executed before each test, while @BeforeClassruns once before the entire test fixture. If your test class has ten tests, @Beforecode will be executed ten times, but @BeforeClasswill be executed only once.

标记的代码@Before在每次测试之前执行,而@BeforeClass在整个测试装置之前运行一次。如果您的测试类有 10 个测试,则@Before代码将执行 10 次,但@BeforeClass只会执行一次。

In general, you use @BeforeClasswhen multiple tests need to share the same computationally expensive setup code. Establishing a database connection falls into this category. You can move code from @BeforeClassinto @Before, but your test run may take longer. Note that the code marked @BeforeClassis run as static initializer, therefore it will run before the class instance of your test fixture is created.

通常,@BeforeClass当多个测试需要共享相同的计算成本高的设置代码时使用。建立数据库连接就属于这一类。您可以将代码从 移动@BeforeClass@Before,但您的测试运行可能需要更长的时间。请注意,标记的代码@BeforeClass作为静态初始化程序运行,因此它将在创建测试夹具的类实例之前运行。

In JUnit 5, the tags @BeforeEachand @BeforeAllare the equivalents of @Beforeand @BeforeClassin JUnit 4. Their names are a bit more indicative of when they run, loosely interpreted: 'before each tests' and 'once before all tests'.

JUnit 5 中,标签@BeforeEach@BeforeAll是JUnit 4 中的@Before和等价物。@BeforeClass它们的名称更能说明它们何时运行,松散地解释为:“每次测试之前”和“所有测试之前一次”。

回答by Joby Wilson Mathews

Difference between each annotation are :

每个注释之间的区别是:

+-------------------------------------------------------------------------------------------------------+
|                                       Feature                            |   Junit 4    |   Junit 5   |
|--------------------------------------------------------------------------+--------------+-------------|
| Execute before all test methods of the class are executed.               | @BeforeClass | @BeforeAll  |
| Used with static method.                                                 |              |             |
| For example, This method could contain some initialization code          |              |             |
|-------------------------------------------------------------------------------------------------------|
| Execute after all test methods in the current class.                     | @AfterClass  | @AfterAll   |
| Used with static method.                                                 |              |             |
| For example, This method could contain some cleanup code.                |              |             |
|-------------------------------------------------------------------------------------------------------|
| Execute before each test method.                                         | @Before      | @BeforeEach |
| Used with non-static method.                                             |              |             |
| For example, to reinitialize some class attributes used by the methods.  |              |             |
|-------------------------------------------------------------------------------------------------------|
| Execute after each test method.                                          | @After       | @AfterEach  |
| Used with non-static method.                                             |              |             |
| For example, to roll back database modifications.                        |              |             |
+-------------------------------------------------------------------------------------------------------+

Most of annotations in both versions are same, but few differs.

两个版本中的大部分注释都是相同的,但很少有不同。

Reference

参考

Order of Execution.

执行顺序。

Dashed box -> optional annotation.

虚线框 -> 可选注释。

enter image description here

在此处输入图片说明

回答by Dhyan Mohandas

Before and BeforeClass in JUnit

JUnit 中的 Before 和 BeforeClass

The function @Beforeannotation will be executed before each of test function in the class having @Testannotation but the function with @BeforeClasswill be execute only one time before all the test functions in the class.

函数@Before注解会在类中每一个带有@Test注解的测试函数之前执行,但带有注解的函数@BeforeClass只会在类中所有测试函数之前执行一次。

Similarly function with @Afterannotation will be executed after each of test function in the class having @Testannotation but the function with @AfterClasswill be execute only one time after all the test functions in the class.

类似地,带有@After注解的函数将在类中每个带有注解的测试函数之后执行,@Test但带有注解的函数@AfterClass只会在类中的所有测试函数之后执行一次。

SampleClass

样本类

public class SampleClass {
    public String initializeData(){
        return "Initialize";
    }

    public String processDate(){
        return "Process";
    }
 }

SampleTest

样品测试

public class SampleTest {

    private SampleClass sampleClass;

    @BeforeClass
    public static void beforeClassFunction(){
        System.out.println("Before Class");
    }

    @Before
    public void beforeFunction(){
        sampleClass=new SampleClass();
        System.out.println("Before Function");
    }

    @After
    public void afterFunction(){
        System.out.println("After Function");
    }

    @AfterClass
    public static void afterClassFunction(){
        System.out.println("After Class");
    }

    @Test
    public void initializeTest(){
        Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
    }

    @Test
    public void processTest(){
        Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
    }

}

Output

输出

Before Class
Before Function
After Function
Before Function
After Function
After Class

In Junit 5

在 Junit 5

@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll

回答by kreker

import org.junit.Assert
import org.junit.Before
import org.junit.BeforeClass
import org.junit.Test

class FeatureTest {
    companion object {
        private lateinit var heavyFeature: HeavyFeature
        @BeforeClass
        @JvmStatic
        fun beforeHeavy() {
            heavyFeature = HeavyFeature()
        }
    }

    private lateinit var feature: Feature

    @Before
    fun before() {
        feature = Feature()
    }

    @Test
    fun testCool() {
        Assert.assertTrue(heavyFeature.cool())
        Assert.assertTrue(feature.cool())
    }

    @Test
    fun testWow() {
        Assert.assertTrue(heavyFeature.wow())
        Assert.assertTrue(feature.wow())
    }
}

Same as

与...一样

import org.junit.Assert
import org.junit.Test

 class FeatureTest {
    companion object {
        private val heavyFeature = HeavyFeature()
    }

    private val feature = Feature()

    @Test
    fun testCool() {
        Assert.assertTrue(heavyFeature.cool())
        Assert.assertTrue(feature.cool())
    }

    @Test
    fun testWow() {
        Assert.assertTrue(heavyFeature.wow())
        Assert.assertTrue(feature.wow())
    }
}