Last Updated: February 25, 2016
·
1.851K
· xeraa

Log the duration of a JUnit test

Logging the duration of a unit test can help debugging performance issues - especially on a remote server like Jenkins. You can of course resort to Surefire reports, but having everything in the general log makes it much easier to correlate issues.

JUnit provides rules to easily add this functionality. Add it to your testing base class and you are good to go:

@Rule
public TestRule watcher = new TestWatcher() {
    private long start;
    protected void starting(Description description) {
        logger.info("Starting test: " + description.getMethodName());
        start = System.currentTimeMillis();
    }

    @Override
    protected void finished(Description description){
        long end = System.currentTimeMillis();
        logger.info("Test " + description.getMethodName() + " took " + (end - start) + "ms");
    }
};