简体   繁体   English

使用 Java 使用 TestNG 从基类扩展

[英]Extending from base class with TestNG with java

I am writing some test classes and extending from base test class.我正在编写一些测试类并从基础测试类扩展。 But the problem is even though I lock the isInited variable it runs once for each class.但问题是即使我锁定了 isInited 变量,它也为每个类运行一次。 It should be run once and initialize it after that it should not be called again but it calls 3 times since I have 3 classes that extends from base class.它应该运行一次并在之后对其进行初始化,之后不应再次调用它,但它会调用 3 次,因为我有 3 个从基类扩展的类。 Please see below.请参阅下文。

Java 1.8 and TestNG 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
}


Looks like you're trying to use Singleton pattern.看起来您正在尝试使用单例模式。 I would suggest to read this article, there are clear explanation and clear implementation examples as well - https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples#lazy-initialization我建议阅读这篇文章,有清晰的解释和清晰的实现示例 - https://www.journaldev.com/1377/java-singleton-design-pattern-best-practices-examples#lazy-initialization

There are a lot of different ways to initialize it, but I would suggest to start with Lazy one - the link above follows it directly.有很多不同的初始化方法,但我建议从懒惰的方法开始 - 上面的链接直接跟随它。

Hope this will help.希望这会有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM