junit Custom Test Rules Custom @TestRule by implementation

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Insert
> Step 2: And Like the video. BONUS: You can also share it!

Example

This is especially useful if we have a class that we want to extend in the rule. See example below for a more convenient method.

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
            }
        }
    }
    
}


Got any junit Question?