JUnit测试用例中的Log4j

时间:2011-11-25 18:18:39

标签: spring junit log4j

我有一个有一个记录器成员的spring bean,我使用该记录器来记录一些动作 我还写了一个使用SpringJUnit4ClassRunner的测试用例。我已经使用属性文件配置了Log4j,并且在每个测试用例中,我使用以下属性初始化记录器:

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

当我进行测试时,它会给我一个警告

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.

但是,我的bean中的记录器将消息写入log4j.properties中的指定位置,即它工作正常。 为什么log4j会给我这样的警告?

3 个答案:

答案 0 :(得分:11)

我想将我的log4j配置保留在默认的类路径之外,以便使用不同的单元测试记录和&生产。我通过继承SpringJUnit4ClassRunner并使用静态类初始化器来解决它。

// 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 );
  }
}

改变测试:

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

现在在调用Spring测试运行器之前配置了log4j。

答案 1 :(得分:5)

我认为原因是SpringJUnit4ClassRunner中的这段代码

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

如果您不希望看到有关log4j的警告,请按照@DN建议将log4j.properties文件添加到您的应用程序类路径中,如果您使用maven目录结构,请将log4j.properties文件添加到(src /主要/资源)将消除警告。

答案 2 :(得分:2)

因为Runner在Log4J初始化之前执行了。