Junit @ Before / @之后叫什么顺序? [英] What order are the Junit @Before/@After called?

查看:507
本文介绍了Junit @ Before / @之后叫什么顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个集成测试套件。我有一个 IntegrationTestBase 类,用于我要扩展的所有测试。这个基类有 @Before public void setUp())和 @After public void tearDown())建立API和数据库连接的方法。我一直在做的只是在每个测试用例中重写这两个方法并调用 super.setUp() super.tearDown()。然而,如果有人忘记调用超级或将它们放在错误的位置并且抛出异常并且忘记在最后或者其他事情中调用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


超级类的 @Before 方法将在当前c的方法之前运行小姐,除非他们在当前班级被覆盖。没有定义其他排序。

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


超类中声明的 @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 / @之后叫什么顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆