JUnit on steroids

Starting version 4.7 JUnit introduces a powerful new concept allowing to hook directly inside JUnit’s test execution workflow.

A number of hooks are already available:

* bundled ones: ExpectedException, Timeout, ErrorCollector, TemporaryFolder
* concurrent test execution
* fit facility

Following is my addition facilitating tests execution under different logging level.

public class LoggerRule implements MethodRule {

    private final Logger logger;
    private final Level[] levels;

    public LoggerRule(final Logger logger) {
        this(logger, Level.OFF, Level.ALL);
    }

    public LoggerRule(final Logger logger, final Level ... levels) {
        this.logger = logger;
        this.levels = levels;
    }

    public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {
        return new Statement() {
            public void evaluate() throws Throwable {
                for (final Level level : LoggerRule.this.levels) {
                    LoggerRule.this.logger.setLevel(level);
                    base.evaluate();
                }
            }
        };
    }

}

Simply declare it in your test class and tests will be executed levels.length time, each time with a different Level. No more bugs due to bad logs!

public class MyTest {

    @Rule
    public final LoggerRule loggerRule = new LoggerRule(Logger.getLogger("myLogger"), Level.OFF, Level.ALL);

    @Test
    public void test() {
        ...
    }

}