junit
JUnit Rules Example
The implementation of a Rule might look like this:
import org.junit.rules.TestRule; import org.junit.runner.Description; import org.junit.runners.model.Statement; public class LoggingRule implements TestRule { public class LoggingStatement extends Statement { private final Statement statement; public LoggingStatement(Statement aStatement, String aName) { statement = aStatement; } @Override public void evaluate() throws Throwable { System.out.println("before: " + name); statement.evaluate(); System.out.println("after: " + name); } } private final String name; public LoggingRule(String aName) { name = aName; } @Override public Statement apply(Statement statement, Description description) { System.out.println("apply: " + name); return new LoggingStatement(statement, name); } }
A test class using this Rule might look like this:
import org.junit.ClassRule; import org.junit.Rule; import org.junit.Test; public class RuleTest { @ClassRule public static LoggingRule classRule = new LoggingRule("classrule"); @Rule public static LoggingRule rule = new LoggingRule("rule"); @Test public void testSomething() { System.out.println("In TestSomething"); assertTrue(true); } @Test public void testSomethingElse() { System.out.println("In TestSomethingElse"); assertTrue(true); } }
Output:
apply: classrule
before: classrule
apply: rule
before: rule
In TestSomething
after: rule
apply: rule
before: rule
In TestSomethingElse
after: rule
after: classrule
Related Article:
Reference: Rules in JUnit 4.9 (beta 3) from our JCG partner Jens Schauder at the Schauderhaft blog