【问题标题】:Extending from base class with TestNG with java使用 java 的 TestNG 从基类扩展
【发布时间】:2020-06-07 03:21:42
【问题描述】:

我正在编写一些测试类并从基础测试类扩展。但问题是即使我锁定了 isInited 变量,它为每个类运行一次。它应该运行一次并对其进行初始化,之后不应再次调用它,但它调用了 3 次,因为我有 3 个从基类扩展的类。请看下文。

Java 1.8 和 TestNG


public class BaseTest(){
private static isInited;
@BeforeClass
  public void init(){
  synchronized (BaseTest.class) {
 //here even though I lock and initialize the variable this code is still called once for each class. I do not understand why this happens?
      if (!isInited) {
        //do some init 
        isInited=true;
     }
  }
}

public class TestClass1 extends BaseTest{

@BeforeClass
  public void setup(){
      //setup somethings
  }

  //test methods
}


public class TestClass2 extends BaseTest{

@BeforeClass
  public void setup(){
      //setup somethings
  }

  //test methods
}

public class TestClass3 extends BaseTest{

@BeforeClass
  public void setup(){
      //setup somethings
  }

  //test methods
}


【问题讨论】:

  • 这就是“@BeforeClass”的行为方式,它将在扩展它的每个测试类之前运行。如果您愿意,可以将其更改为“@BeforeTest”并将所有测试类组合在一个测试标签下,或者您可以使用“@BeforeSuite”并将其组合在一个套件标签下。

标签: java testing testng testng.xml testng-annotation-test


【解决方案1】:

看起来您正在尝试使用单例模式。我建议阅读这篇文章,有清晰的解释和清晰的实现示例 - https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples#lazy-initialization

有很多不同的方法来初始化它,但我建议从 Lazy 开始 - 上面的链接直接跟随它。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2015-09-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 1970-01-01
    • 2018-10-10
    • 2012-09-30
    • 1970-01-01
    相关资源
    最近更新 更多