Junit @Before/@After 的调用顺序是什么? [英] What order are the Junit @Before/@After called?
问题描述
我有一个集成测试套件.我有一个 IntegrationTestBase
类来扩展我的所有测试.这个基类有一个 @Before
(public void setUp()
) 和 @After
(public void tearDown()
>) 方法来建立 API 和 DB 连接.我一直在做的只是在每个测试用例中覆盖这两个方法并调用 super.setUp()
和 super.tearDown()
.但是,如果有人忘记调用 super 或将它们放在错误的位置并抛出异常并且他们忘记在 finally 中调用 super 或其他东西,这可能会导致问题.
I have an Integration Test Suite. I have a IntegrationTestBase
class for all my tests to extend. This base class has a @Before
(public void setUp()
) and @After
(public void tearDown()
) method to establish API and DB connections. What I've been doing is just overriding those two methods in each testcase and calling super.setUp()
and super.tearDown()
. However this can cause problems if someone forgets to call the super or puts them at the wrong place and an exception is thrown and they forget to call super in the finally or something.
我想要做的是在基类 final
上创建 setUp
和 tearDown
方法,然后添加我们自己的带注释的 >@Before
和 @After
方法.做一些初始测试,它似乎总是按以下顺序调用:
What I want to do is make the setUp
and tearDown
methods on the base class final
and then just add our own annotated @Before
and @After
methods. Doing some initial tests it appears to always call in this order:
Base @Before
Test @Before
Test
Test @After
Base @After
但我有点担心订单无法保证并且可能会导致问题.我环顾四周,并没有看到有关该主题的任何内容.有谁知道我是否可以这样做并且没有任何问题?
but I'm just a little concerned that the order isn't guaranteed and that it could cause problems. I looked around and haven't seen anything on the subject. Does anyone know if I can do that and not have any problems?
代码:
public class IntegrationTestBase {
@Before
public final void setUp() { *always called 1st?* }
@After
public final void tearDown() { *always called last?* }
}
public class MyTest extends IntegrationTestBase {
@Before
public final void before() { *always called 2nd?* }
@Test
public void test() { *always called 3rd?* }
@After
public final void after() { *always called 4th?* }
}
推荐答案
是的,这种行为是有保证的:
Yes, this behaviour is guaranteed:
超类的 @Before
方法将在当前类的方法之前运行,除非它们在当前类中被覆盖.没有定义其他排序.
The
@Before
methods of superclasses will be run before those of the current class, unless they are overridden in the current class. No other ordering is defined.
超类中声明的 @After
方法将在当前类的方法之后运行,除非它们在当前类中被覆盖.
The
@After
methods declared in superclasses will be run after those of the current class, unless they are overridden in the current class.
这篇关于Junit @Before/@After 的调用顺序是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!