What is the difference between @BeforeTest and @BeforeSuit annotation? I have 2 methods with @Test annotation and one @BeforeTest method. When I ran it, a @BeoforeTest method was executed only once. Shouldn't it run before every @Test method?
4 Answers
You may refer this example,
https://stackoverflow.com/a/50814147/9405154
If you want to call annotation before every Test method, You need to use @BeforeMethod annotation. Both @BeforeTest and @BeforeSuite will call only once on execution, They just have different approach on .XML suite execution.

- 3,955
- 2
- 27
- 51
@BeforeTest will run per class
You probably want per test method,then use @BeforeMethod:
The annotated method will be run before each test method.
@BeforeTest: The annotated method will be run before any test method belonging to the classes inside the tag is run
@BeforeTest
this annotation will run before every test method for example
@BeforeTest
public void Setup()
{
System.out.println("before test");
}
@Test
public void test1()
{
System.out.println("Test1");
}
@Test
public void test2()
{
System.out.println("Test2");
}
Then output is as
before test
Test1
before test
Test2
where as @BeforeSuite
this annotation will run @beforeclass
-
BeforeTest call only once, BeforeMethod call on every Test method – Ishita Shah Nov 19 '18 at 04:50
@BeforeTest
-
Any code written in the method with this annotation will run once for all methods with annotation
@Test
inside a class.This is best suited for condition which is a prerequisite for all tests e.g. test 1 is view user profile, test 2 is add item to cart, test 3 is manage address, these tests are dependent on a condition that user should be logged in, so we can write login functionality in a method with
@BeforeTest
annotation.It is present in same class in which
@Test
method is written.This is mainly applied at method level.
@BeforeSuite
-
Any code written in the method with this annotation will run once in complete suite life cycle i.e. for complete
testng.xml
.This is best suited for initializing config files,creating database connections etc.
This annotation is mainly used in Base class of the class in which
@Test
method is present
@Edit - Changed the @BeforeTest annotation details

- 4,389
- 2
- 18
- 21
-
1BeforeTest call only once, where BeforeMethod call on every Test method – Ishita Shah Nov 19 '18 at 05:06
-
1@IshitaShah - Thanks for correcting me. This -1 is also a good learning. I will correct it so that others will not divert in wrong direction.... – Amit Jain Nov 19 '18 at 05:57