JUnit测试用例中的Log4j

mak*_*aks 6 junit spring log4j

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

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

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

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.
Run Code Online (Sandbox Code Playgroud)

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

wbd*_*rby 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 );
  }
}
Run Code Online (Sandbox Code Playgroud)

测试的变化:

@RunWith(JUnit4ClassRunner.class)
@ContextConfiguration
@TransactionConfiguration
@Transactional
public class LmpDaoImplTest extends AbstractTransactionalJUnit4SpringContextTests {
...
Run Code Online (Sandbox Code Playgroud)

现在,在调用Spring测试运行器之前配置log4j.


Pra*_*nti 5

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

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

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