@BeforeClass 和继承 - 执行顺序 [英] @BeforeClass and inheritance - order of execution

查看:33
本文介绍了@BeforeClass 和继承 - 执行顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象基类,我将其用作单元测试 (TestNG 5.10) 的基础.在这个类中,我为我的测试初始化​​整个环境,设置数据库映射等.这个抽象类有一个带有 @BeforeClass 注释的方法,它执行初始化.

I have an abstract base class, which I use as a base for my unit tests (TestNG 5.10). In this class, I initialize the whole environment for my tests, setting up database mappings, etc. This abstract class has a method with a @BeforeClass annotation which does the initialization.

接下来,我使用具有 @Test 方法和 @BeforeClass 方法的特定类扩展该类.这些方法执行特定于类的环境初始化(例如,将一些记录放入数据库).

Next, I extend that class with specific classes in which I have @Test methods and also @BeforeClass methods. These methods do class-specific initialization of the environment (e.g. put some records into the database).

我如何强制执行 @BeforeClass 注释方法的特定顺序?我需要在扩展类之前执行抽象基类中的那些.

How I can enforce a specific order of the @BeforeClass annotated methods? I need the ones from the abstract base class to be executed before the ones of the extending class.

示例:

abstract class A {
    @BeforeClass
    doInitialization() {...}
}

class B extends A {
    @BeforeClass
    doSpecificInitialization() {...}

    @Test
    doTests() {...}
}

预期订单:

A.doInitialization
B.doSpecificInitialization
B.doTests

实际订单:

B.doSpecificInitialization // <- crashes, as the base init is missing
(A.doInitialization        // <---not executed
 B.doTests)                // <-/

推荐答案

不要将 @BeforeClass 放在 abstract 类上.从每个子类调用它.

Don't put the @BeforeClass on the abstract class. Call it from each subclass.

abstract class A {
    void doInitialization() {}
}

class B extends A {
    @BeforeClass
    void doSpecificInitialization() {
        super.doInitialization();
    }

    @Test
    void doTests() {}
}

似乎 TestNG 有 @BeforeClass(dependsOnMethods={"doInitialization"}) - 试一试.

Seems like TestNG has @BeforeClass(dependsOnMethods={"doInitialization"}) - give it a try.

这篇关于@BeforeClass 和继承 - 执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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