Official Documentations are so unclear and mostly ambiguous. This is why many don't like to read it. Not to mention no real-life examples shown.
If you are trying to get code to run once before every test, then you are looking for @BeforeMethod, not @BeforeTest. Because each of your tests independently considered methods.
@BeforeMethod runs before each method. I see you have two methods with the names test1() and test2(). Expect BeforeMethod to run before each of them.
@BeforeTest runs only once before ALL of your tests (test-methods). In Selenium, WebDriver is called once, this is better practice for testing.
@BeforeMethod will invoke WebDriver before each test, this is not good practice, especially when you have regression tests with hundreds of them to run.
For example, if you run this code (these are separate classes, not inner to each other, only showing for demonstration purposes here):
public class TestClass extends Base {
@Test
public void test1() {
System.out.println("Running Test 1");
}
@Test
public void test2() {
System.out.println("Running Test 2");
}
}
public class Base {
@BeforeTest
public void beforeTest() {
System.out.println("Before Test");
}
@AfterTest
public void afterTest() {
System.out.println("After Test");
}
@BeforeMethod
public void beforeMethod() {
System.out.println("Before Method");
}
@AfterMethod
public void afterMethod() {
System.out.println("After Method");
}
}
And you will get this as an output:
Before Test
Before Method
Running Test 1
After Method
Before Method
Running Test 2
After Method
After Test
As you can see BeforeMethods run before each test while BeforeTest and AfterTest run only once before and after completing ALL tests.
Hope this clarified the difference for you.