通過實現自定義 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
            }
        }
    }
    
}