0

我正在编写一些测试类并从基础测试类扩展。但问题是即使我锁定了 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
}


4

1 回答 1

1

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

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

希望这会有所帮助。

于 2020-02-23T11:27:19.013 回答