High level, I have JUnit test class which is pretty straightforward. I have several @Tests and a single @Before which does some set up. For one test case, the setup varies (I don't want it to be run).
From some searching I found https://stackoverflow.com/a/13017452/413254. This suggests creating a @Rule which checks for a particular annotation and executes the @Before statement.
My confusion is around how to execute the @Before method in the rule. Is there a way to do that? Or do I need to pass in the test class itself and execute the @before method (setup()
in the example below)?
public class NoBeforeRule implements TestRule {
@Override
public Statement apply(final Statement base, final Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
if (description.getAnnotation(NoBefore.class) == null) {
// Is there something like `base.executeAllTheBefores()'
}
base.evaluate();
}
};
}
}
The relevant test code:
@Rule public NoBeforeRule mNoBeforeRule = new NoBeforeRule(this);
@Before
@Override
public void setup() {
}
@Test
public void testNeedSetup() {
// this should run setup()
}
@NoBefore
@Test
public void testNoSetup() {
// this should NOT run setup()
}