Aravind Shankar
Aravind Shankar

Reputation: 53

How to use @BeforeTest in separate java file in testng

I am writing automation testing script for a project . Here , I will have many test classes for which I will be using same @BeforeTest Method . I tried by creating a base class (in which I declared before test method ) and extending them in my test classes . But its not working . Is there any other way to have a common beforeTest method in a seperate java file and use it for all my test classes .

Upvotes: 1

Views: 1044

Answers (2)

Pablo Miranda
Pablo Miranda

Reputation: 369

Using a base class for my other classes works for me. You should use @BeforeMethod for your needs since @BeforeTest is used to run any @Test included in the <test> tag in a testNG.xml file.

public class BaseClass {
  @BeforeMethod
  public void before() {
    System.out.println("Before method");
  }  
}

and then

public class ATestClass extends BaseClass {
  @Test
  public void testOne() {
    System.out.println("testOne run");
  }
  @Test
  public void testTwo() {
    System.out.println("testTwo run");
  }
}

gave me the result

enter image description here

Try it out!

Upvotes: 2

DHARMENDRA SINGH
DHARMENDRA SINGH

Reputation: 615

If you are using PowerMockito or Mockito you can achieve by following.

public abstract class ParentClass{
    @Before
    public void init() {
        System.out.println("inniinii");
       }
}

@RunWith(PowerMockRunner.class)
public class ChildClass extends ParentClass{
@Test
public void test() {
    System.out.println("hello test");
      }
}

Upvotes: 0

Related Questions