0

I am writing a gradle script that runs all tests before making a build.

test {
    filter {
        includeTestsMatching "*TestAll*"
        includeTestsMatching "*ExtensionValidatorTest*"
        ........
    }
}

I have three tests of different versions(v1,v2,v3).

TestAll.java

package .....v1;//v2 for version 2 and v3 for version 3

@RunWith(Suite.class)
@Suite.SuiteClasses({
      A.class,
      B.class,
      ......
})
public class TestAll {

    @BeforeClass
    public static void setUp() {//connection to database
         ........
    }

    @AfterClass
    public static void tearDown()  {//close database connection 
         ........
    }
}

When I run gradle test connection to database is broken after execution of a particular TestAll. I do not want to change the TestAll files of any version as they can be run and tested independently. How can I make gradle run only setUp once(of any version)which establishes connection, then run all the TestAll method in v1,v2 and v3 and finally teardown(of any version) which terminates database connection.

Ros
  • 73
  • 2
  • 9

1 Answers1

0

Gradle won't help you with this. There are following methods in Gradle DSL:

test {
   beforeSuite{...} 

   afterSuite{...}
}

However, they execute outside of the test runtime scope and intended for logging. You only can achieve this using a testing framework.

TestNG provides a simple solution - @BeforeSuite and @AfterSuite annotations, that are actually run once before and after the entire suite.

Unfortunately, JUnit doesn't have a built-in solution for that, since test isolation is its core concept. Nevertheless, you still can make your own. You need to encapsulate database-related API into a singleton class:

public class DbContainer() {
   private static DbContainer container;

   private DbContaner() {}

   public DbContainer getInstance() {
      if (container == null) {
         container = new DbContainer()
      }
      return container;
   }

   public void openConnection() {
      // ...
   }

   public void closeConnection() {
      // ...
   }

   // here is your database API methods
}

Then you can share this instance between test methods and classes using @ClassRule annotation:

   @ClassRule
   public static DbContainer db = DbContainer.getInstance(); 

   @Test
   public void someTest() {
      db.query(...)
   }

Note: provided solution is not thread-safe and doesn't suit the parallel execution. Some additional effort is required to achieve it.

Yevhen Danchenko
  • 1,039
  • 2
  • 9
  • 17