You can do this with JUnit Rules.
There's a whole blog post dedicated to exactly your question here, but in short, you do the following:
- Create a class that implements the
org.junit.rules.TestRule
interface. This interface contains the following method:
Statement apply(Statement base, Description description);
The base
argument is actually your test, which you run by calling base.execute()
-- well, the apply()
method actually returns a Statement
anonymous instance that will do that. In your anonymous Statement
instance, you'll add the logic to determine whether or not the test should be run. See below for an example of a TestRule
implementation that doesn't do anything except execute your test -- and yes, it's not particularly straighforward.
- Once you've created your
TestRule
implementation, then you need to add the following lines to to your JUnit Test Class:
@Rule
public MyTestRuleImpl conditionalTests;
Remember, the field must be public.
And that's it. Good luck -- as I said, you may have to hack a little, but I believe there's a fair amount explained in the blog post. Otherwise, there should be other information on the internets (or in the JUnit sourc code).
Here's a quick example of a TestRule implementation that doesn't do anything.
public abstract class SimpleRule implements TestRule {
public Statement apply(final Statement base, final Description description) {
return new Statement() {
public void evaluate() throws Throwable {
try {
base.evaluate();
} catch (Throwable t) {
t.printStackTrace();
}
}
};
}
}