0

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. 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. Please see below.

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


Lisa
  • 129
  • 1
  • 1
  • 8
  • 1
    That is how the behaviour is of '@BeforeClass' it will run before every Test Class which extends it. If you want you can change it to '@BeforeTest' and club all your test classes under one test tag or you can use '@BeforeSuite' and club together under one suite tag. – Mrunal Gosar Feb 23 '20 at 14:32

1 Answers1

1

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

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.

Villa_7
  • 508
  • 4
  • 14