Reputation: 75
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.
Upvotes: 3
Views: 246
Reputation: 4935
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 {
// ........
}
Upvotes: 0
Reputation: 1652
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
Upvotes: 5