javaannotationstestngtestng-annotation-test

Common annotations used in different test classes


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.


Solution

  • 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