Skip to content

Instantly share code, notes, and snippets.

@RainerW
Created April 11, 2012 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RainerW/2358589 to your computer and use it in GitHub Desktop.
Save RainerW/2358589 to your computer and use it in GitHub Desktop.
JUnit MethodRule / TestRule solution?
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.runner.Description;
import org.junit.runners.model.FrameworkMethod;
import org.junit.runners.model.Statement;
// ************ draft for new rule interface ************
interface RuleStatement {
Statement apply(Statement base, RuleParameter parameter);
}
interface RuleParameter {
Description getDescriptor();
Class<?> getTestClass();
// more ? e.g.:
void failTest(String message); // like fail()
void ignoreTest(String message); // so i don't need to throw a AssumtionViolation
}
interface MethodParameter extends RuleParameter{
Object getTestInstance();
Method getTestMethod();
}
interface ClassParameter extends RuleParameter {
// Just a marker interface to switch rule logic
}
// ************ implement you rules ************
class SampleClassRule implements RuleStatement {
public Statement apply(Statement base, RuleParameter parameter) {
// ...
}
}
class SampleMethodRule implements RuleStatement {
public Statement apply(Statement base, RuleParameter parameter) {
if(parameter instanceof ClassParameter) { fail(); ) }
// ...
}
}
// ************ usage in tests ************
public class SampleRulesTest {
@ClassRule
public RuleStatement aClassRule = new SampleClassRule();
@Rule
public RuleStatement aTestMethodRule = new SampleMethodRule();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment