JUNIT : run setup only once for a large number of test classes JUNIT : run setup only once for a large number of test classes database database

JUNIT : run setup only once for a large number of test classes


With JUnit4 test suite you can do something like this :

@RunWith(Suite.class)@Suite.SuiteClasses({ Test1IT.class, Test2IT.class })public class IntegrationTestSuite{    @BeforeClass    public static void setUp()    {        System.out.println("Runs before all tests in the annotation above.");    }    @AfterClass    public static void tearDown()    {        System.out.println("Runs after all tests in the annotation above.");    }}

Then you run this class as you would run a normal test class and it will run all of your tests.


JUnit doesn't support this, you will have to use the standard Java work-arounds for singletons: Move the common setup code into a static code block and then call an empty method in this class:

 static {     ...init code here... } public static void init() {} // Empty method to trigger the execution of the block above

Make sure that all tests call init(), for example my putting it into a @BeforeClass method. Or put the static code block into a shared base class.

Alternatively, use a global variable:

 private static boolean initialize = true; public static void init() {     if(!initialize) return;     initialize = false;     ...init code here... }


Create one base class for all tests:

public class BaseTest {    static{        /*** init code here ***/    }   }

and every test should inherit from it:

public class SomeTest extends BaseTest {}