通过实现自定义 TestRule
如果我们有一个我们想在规则中扩展的类,这将特别有用。有关更方便的方法,请参见下面的示例。
import org.junit.rules.TestRule;
import org.junit.runners.model.Statement;
public class AwesomeTestRule implements TextRule {
@Override
public Statement apply(Statement base, Description description) {
return new AwesomeStatement(base);
}
private static class AwesomeStatement extends Statement {
private Statement base;
public AwesomeStatement(Statement base) {
this.base = base;
}
@Override
public void evaluate() throws Throwable {
try {
// do your magic
base.evaluate(); // this will call Junit to run an individual test
} finally {
// undo the magic, if required
}
}
}
}