Log4j in JUnit test case

I have a spring bean that has a log member and I use this logger to log some activities.
I also wrote a test case that uses SpringJUnit4ClassRunner . I configured Log4j with the 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 the 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 to the specified location in log4j.properties, that is, it works fine. Why does log4j give me such warnings?

+6
source share
3 answers

I think the reason for this code is 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 to see a warning about log4j, just follow as @DN suggested simply adding the log4j.properties file to your application class path. If you use the maven directory structure, add the log4j.properties file to (src / main / resources), which will clear the warning.

+5
source

I wanted to save the log4j configuration from the default class in order to use different logging with unit tests and production. I worked around it, 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 ); } } 

Test change:

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

Log4j is now configured before invoking the Spring test runner.

+11
source

Because Runner runs runs before initializing Log4J.

+2
source

Source: https://habr.com/ru/post/902410/


All Articles