views:

4330

answers:

4

Looking at the last JUnit test case I wrote, I called log4j's BasicConfigurator.configure() method inside the class constructor. That worked fine for running just that single class from Eclipse's "run as JUnit test case" command. But I realize it's incorrect: I'm pretty sure our main test suite runs all of these classes from one process, and therefore log4j configuration should be happening higher up somewhere.

But I still need to run a test case by itself some times, in which case I want log4j configured. Where should I put the configuration call so that it gets run when the test case runs standalone, but not when the test case is run as part of a larger suite?

+4  A: 

If you have a log4j configuration file on the classpath during your test run, it should be picked up. Alternately, you can specify the location of the configuration file directly by saying:

-Dlog4j.configuration=<path to properties file>

to your test runner configuration. See also the online documentation.

Paul Morie
+3  A: 

You may want to look into to Simple Logging Facade for Java (SLF4J). It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.

James McMahon
+3  A: 

I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)

araqnid
+1  A: 

Here is some code which does that (just search for "isConfigured").

Yishai