Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where do I configure log4j in a JUnit test class?

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?

like image 842
skiphoppy Avatar asked May 18 '09 15:05

skiphoppy


People also ask

How do I test a logger message in JUnit?

@StefanoL: If a logger is defined with private static final Logger LOGGER = Logger. getLogger(someString); , you can still access it from unit tests with Logger. getLogger(someString); , modify it and add handlers (as in the accepted answer).

How do I change my log4j configuration?

The simplest is to put a log4j. xml on the classpath. Then add the monitorInterval="30" attribute to the opening configuration tag. This tells log4j to check the file for changes every 30 seconds.


1 Answers

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)

like image 178
araqnid Avatar answered Sep 28 '22 01:09

araqnid