Here are a couple of different ways of suppressing logging when running unit tests. If you are using apache commons logging then you can suppress logging with the following code:
LogFactory.getFactory().setAttribute( "org.apache.commons.logging.Log", "org.apache.commons.logging.impl.NoOpLog");
If running your unit tests with JUnit, it is probably best to put this code in the setUp() method. However, if you only wanted it suppressed on particular tests, it could go at the top of the test method instead. Bear in mind that if the logger is a static in the class you are testing, you may need to then reset the attribute at the end of the test method, otherwise, any tests being run after that one will also have their logging suppressed.
If you run your unit tests within an IDE, you may want to see the logging, but not see the logging when you actually run the build of your project with something like Maven. Thankfully, there is a very simple answer to this if you are using Maven. The maven-surefire-plugin is responsible for running the tests and there is a configuration option which needs to be specified to redirect all the test output to file instead of to the console. This keeps your build reports much cleaner as you aren’t interested in seeing the logging messages. As a bonus, since all output is saved to file, exceptions will also be output to file, so whenever exceptions are thrown in the methods being tested, the stack trace wont show up in the build report.
The configuration option that needs specifying is <redirectTestOutputToFile> and this needs to be set to true, as shown below.
<plugin> <artifactId>maven-surefire-plugin</artifactId> <configuration> <redirectTestOutputToFile>true</redirectTestOutputToFile> </configuration> </plugin>