2

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?

O_K
  • 922
  • 9
  • 14

4 Answers4

1

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.

Ishita Shah
  • 3,955
  • 2
  • 27
  • 51
0

@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

Community
  • 1
  • 1
Ori Marko
  • 56,308
  • 23
  • 131
  • 233
-1

@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

Dev
  • 2,739
  • 2
  • 21
  • 34
Harshit
  • 19
  • 2
-1

@BeforeTest -

  1. Any code written in the method with this annotation will run once for all methods with annotation @Test inside a class.

  2. 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.

  3. It is present in same class in which @Test method is written.

  4. This is mainly applied at method level.

@BeforeSuite -

  1. Any code written in the method with this annotation will run once in complete suite life cycle i.e. for complete testng.xml.

  2. This is best suited for initializing config files,creating database connections etc.

  3. This annotation is mainly used in Base class of the class in which @Test method is present

@Edit - Changed the @BeforeTest annotation details

Amit Jain
  • 4,389
  • 2
  • 18
  • 21
  • 1
    BeforeTest 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