There are several ways to achieve this. The simplest and easiest way is to have a βtestβ that runs at the beginning and end of your package, which set up your database and then sets a global flag. In your @Before and @After tests, you check this flag and, if necessary, configure / disable.
@RunWith(Suite.class) @SuiteClasses({SetupTest.class, RealTest.class, TeardownTest.class});
This is the simplest solution, but it is not very nice, so using TestRule will be a more convenient solution. Take a look at the ExternalResource extension. This implements before and after the logic that surrounds your testing methods. This will allow you to separate the @Before and @After methods to reuse the same code everywhere.
Then for your package you need to implement before and after the logic. Unfortunately, the class annotated with @RunWith (Suite.class) has not actually been created, so you cannot use the constructor of this class, but you can extend Suite . Depending on how you run this, you will need to implement one of the constructors using @RunWith as an example:
public class MySuite extends Suite { public MySuite(Class<?> klass, RunnerBuilder builder) throws InitializationError { this(builder, klass, getAnnotatedClasses(klass));
Then run the test suite with
@RunWith(MySuite.class)
There are several constructors that are used in different situations, look at the comments next to each of them. You still need to use a global variable so that your Rules do not restart the installation code. The above will work if you want to execute only the setup code, executing the break code is more complicated, but can be done. Let me know if you need it :-)
If you need more flexibility (for example, executing installation code for specific methods only), see my answer to How to define a JUnit method rule in a package? .