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

问题描述

我有一个抽象基类,我将其用作单元测试的基础(TestNG 5.10)。在这个类中,我初始化了测试的整个环境,设置了数据库映射等。这个抽象类有一个带有 @BeforeClass 注释的方法,用于初始化。 / p>

接下来,我使用特定的类扩展该类,其中我有 @Test 方法以及 @BeforeClass 方法。这些方法对类环境进行特定于类的初始化(例如,将一些记录放入数据库中)。



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



示例:

 抽象类A {
@BeforeClass
doInitialization(){...}
}

B类扩展A {
@BeforeClass
doSpecificInitialization(){...}

@Test
doTests(){...}
}

预期订单:

  A.doInitialization 
B.doSpecificInitialization
B.doTests

实际订单:

  B.doSpecificInitialization //<  - 崩溃,因为基本init缺少
(A.doInitialization / /< ---未执行
B.doTests)//< - /


解决方案

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

 抽象类A {
void doInitialization(){}
}

B类扩展A {
@BeforeClass
void doSpecificInitialization(){
super.doInitialization();
}

@Test
void doTests(){}
}

似乎TestNG有 - 试一试。


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.

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).

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.

Example:

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

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

    @Test
    doTests() {...}
}

Expected order:

A.doInitialization
B.doSpecificInitialization
B.doTests

Actual order:

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

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() {}
}

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

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

10-21 05:04