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.

<br />
public class LoggerRule implements MethodRule {</p>
<p>    private final Logger logger;<br />
    private final Level[] levels;</p>
<p>    public LoggerRule(final Logger logger) {<br />
        this(logger, Level.OFF, Level.ALL);<br />
    }</p>
<p>    public LoggerRule(final Logger logger, final Level ... levels) {<br />
        this.logger = logger;<br />
        this.levels = levels;<br />
    }</p>
<p>    public Statement apply(final Statement base, final FrameworkMethod method, final Object target) {<br />
        return new Statement() {<br />
            public void evaluate() throws Throwable {<br />
                for (final Level level : LoggerRule.this.levels) {<br />
                    LoggerRule.this.logger.setLevel(level);<br />
                    base.evaluate();<br />
                }<br />
            }<br />
        };<br />
    }</p>
<p>}<br />

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!

<br />
public class MyTest {</p>
<p>    @Rule<br />
    public final LoggerRule loggerRule = new LoggerRule(Logger.getLogger(&quot;myLogger&quot;), Level.OFF, Level.ALL);</p>
<p>    @Test<br />
    public void test() {<br />
        ...<br />
    }</p>
<p>}<br />