+-------------------------------------------------------------------------------------------------------+
¦ 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. ¦ ¦ ¦
+-------------------------------------------------------------------------------------------------------+
3 回答
标记
@Before
的代码在每次测试之前执行,而@BeforeClass
在整个测试夹具之前运行一次 . 如果您的测试类有十个测试,@Before
代码将被执行十次,但@BeforeClass
将只执行一次 .通常,当多个测试需要共享相同的计算昂贵的设置代码时,您使用
@BeforeClass
. Build 数据库连接属于此类别 . 您可以将代码从@BeforeClass
移动到@Before
,但您的测试运行可能需要更长时间 . 请注意,标记为@BeforeClass
的代码作为静态初始化程序运行,因此它将在创建测试夹具的类实例之前运行 .在JUnit 5中,标签
@BeforeEach
和@BeforeAll
在JUnit 4中等同于@Before
和@BeforeClass
. 它们的名称更能说明它们何时运行,松散地解释:'before each tests'和'once before all tests' .Before and BeforeClass in JUnit
函数
@Before
注释将在具有@Test
注释的类中的每个测试函数之前执行,但具有@BeforeClass
的函数将仅在类中的所有测试函数之前执行一次 .类似地,具有
@After
注释的函数将在具有@Test
注释的类中的每个测试函数之后执行,但具有@AfterClass
的函数将仅在类中的所有测试函数之后执行一次 .SampleClass
SampleTest
Output
In Junit 5
Difference between each annotation are :
两个版本中的大多数注释都是相同的,但很少有区别 .
Reference
Order of Execution.
虚线框 - >可选注释 .