I have some code that needs to run before and after my tests classes. It does not matter how many test classes are running in the middle, it has to run once and only once for the entire collection.
When I run in a suite, it is called at the start and end of the entire suite, this is working as expected, however, I want to be able to run a single test class. In this case, the test class needs to detect that it is running alone and start the pre/post test code.
Is this possible?
You could always implement this by having that code detect if it has already been run, through a static field or some other method, and skip running again. Then, call it unconditionally in the @BeforeClass
of each test.
Calling that code now becomes part of the preconditions for each test, with the custom code taking responsibility for only running when necessary.
You might consider other ways to avoid the problem in the first place: either reduce the environmental dependencies for the tests, or make the code naturally idempotent.
I solved this problem this way:
In MySuite
I added this:
public static Boolean suiteRunning = false;
@ClassRule
public static ExternalResource triggerSuiteRunning = new ExternalResource() {
@Override
protected void before() throws Throwable {
suiteRunning = true;
}
};
Now, in the dependent tests, I know that the suite is running or not and can disable tests:
@BeforeClass
public static void beforeClass() {
Assume.assumeTrue(MySuite.suiteRunning);
}
// --- or ---
@Test
public static void test() {
Assume.assumeTrue(MySuite.suiteRunning);
}