You can use ClassRule
public static class GlobalDataSource extends ExternalResource
private int count = 0;
private DataSource dataSource;
private GlobalDataSource() {};
public static final GlobalDataSource INSTANCE = new GlobalDataSource();
public DataSource get() {
if (dataSource == null) {
throw new IllegalStateException();
}
return dataSource;
}
@Override
protected void before() throws Throwable {
if (count++ == 0) {
dataSource = createDataSource();
}
}
@Override
protected void after() {
if (--count == 0) {
try {
destroyDataSource(dataSource);
} finally {
dataSource = null;
}
}
};
};
In your tests:
@RunWith(JUnit4.class)
public class FooTest {
@ClassRule public static GlobalDataSource source = GlobalDataSource.INSTANCE;
@Test
public void readDataSource() {
...
}
}
Then create a suite:
@RunWith(Suite.class)
@SuiteClasses(FooTest.class, BarTest.class ...)
public class AllTests {
@ClassRule public static GlobalDataSource source = GlobalDataSource.INSTANCE;
}
Be aware that global state in tests can be just as problematic as global state in code. A failure in one test could lead other tests to fail.