Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log4j in JUnit Test case

I have a spring bean which has a logger member and I use that logger to log some actions.
Also I have written a test case which uses SpringJUnit4ClassRunner. I have configured Log4j with a properties file and in each test case I initialize the logger with these properties:

@BeforeClass
public static void init() {
   PropertyConfigurator.configure("src/com/config/log4j.properties");
}

when I run a test it gives me a warning

log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

However, the logger in my bean writes messages into the specified location in log4j.properties, i.e. it works fine. Why does log4j gives me such warnings?

like image 595
maks Avatar asked Nov 25 '11 18:11

maks


2 Answers

I wanted to keep my log4j config out of the default classpath to use different logging with unit tests & production. I worked around it by subclassing SpringJUnit4ClassRunner and using a static class initializer.

// The new test runner
public class JUnit4ClassRunner extends SpringJUnit4ClassRunner {

  static {
    try {
      Log4jConfigurer.initLogging( "classpath:test/log4jconfig.xml" );
    }
    catch( FileNotFoundException ex ) {
      System.err.println( "Cannot Initialize log4j" );
    }
  }

  public JUnit4ClassRunner( Class<?> clazz ) throws InitializationError {
    super( clazz );
  }
}

The Change to the Test:

@RunWith(JUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration
@Transactional
public class LmpDaoImplTest extends AbstractTransactionalJUnit4SpringContextTests {
...

Now log4j is configured before the Spring test runner is invoked.

like image 172
wbdarby Avatar answered Oct 18 '22 00:10

wbdarby


I think reason is this code in SpringJUnit4ClassRunner

 public SpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
    super(clazz);
    if (logger.isDebugEnabled()) {
        logger.debug("SpringJUnit4ClassRunner constructor called with [" + clazz + "].");
    }
    this.testContextManager = createTestContextManager(clazz);
}

If you don't want see the warning regarding log4j, Just do as @DN suggested just add log4j.properties file to your application class path, In case if you use maven directory structure add log4j.properties file to (src/main/resources) that will eliminate the warning.

like image 25
Prasanna Talakanti Avatar answered Oct 18 '22 00:10

Prasanna Talakanti