I have a question regarding annotations like @BeforeTest
or @BeforeMethod
. Is it possible to set a global annotations, so that all my test classes will be use them? I have in my framework over 20 test classes with a lot of test methods. Every test class has preconditions like @BeforeTest
or @BeforeMethod
, but for each test class this preconditions are the same. So I think this might be a good idea, to write a common annotations methods, which could be used in every test class.
Asked
Active
Viewed 130 times
3
-
Use a listener. – Boris the Spider Sep 14 '21 at 19:34
-
@BoristheSpider How can use it? Can you explain this? – Kamil Sep 15 '21 at 05:51
2 Answers
5
Make the code reusable using inheritance. Create a super class DefaultTestCase
:
public class DefaultTestCase{
@BeforeTest
public void beforeTest() {
System.out.println("beforeTest");
}
@BeforeMethod
public void beforeMethod() {
System.out.println("beforeMethod");
}
}
and each test case class extends the DefaultTestCase
:
public class ATest extends DefaultTestCase{
@Test
public void test() {
System.out.println("test");
}
@Test
public void anotherTest() {
System.out.println("anotherTest");
}
}
Output:
beforeTest
beforeMethod
test
beforeMethod
anotherTest

gkatiforis
- 1,588
- 9
- 19
0
Using an implementation of ITestListener
and IClassListener
, you could do as below. onTestStart
would be invoked before each test case and onStart
would be invoked for <test>
in your suite and onBeforeClass
is executed once for each class.
public class MyListener implements ITestListener, IClassListener {
@Override
public void onStart(ITestContext context) {
// Put the code in before test.
beforeTestLogic();
}
@Override
public void onBeforeClass(ITestClass testClass) {
// Put the code in before class.
beforeClassLogic();
}
@Override
public void onTestStart(ITestResult result) {
// Put the code in before method.
beforeMethodLogic();
}
}
Now add the @Listener
annotation to the required test classes:
@Test
@Listener(MyListener.class)
public class MyTest {
// ........
}

Gautham M
- 4,816
- 3
- 15
- 37