我在哪里可以在 JUnit 测试类中配置 log4j? [英] Where do I configure log4j in a JUnit test class?

查看:16
本文介绍了我在哪里可以在 JUnit 测试类中配置 log4j?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

查看我写的最后一个JUnit测试用例,我在类构造函数中调用了log4j的BasicConfigurator.configure()方法.这适用于从 Eclipse 的作为 JUnit 测试用例运行"命令运行单个类.但我意识到这是不正确的:我很确定我们的主要测试套件从一个进程运行所有这些类,因此 log4j 配置应该发生在更高的某个地方.

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.

但有时我仍然需要自己运行一个测试用例,在这种情况下,我需要配置 log4j.我应该把配置调用放在哪里,以便它在测试用例独立运行时运行,而不是在测试用例作为更大套件的一部分运行时运行?

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?

推荐答案

LogManager 类决定在 静态块 在类加载时运行.为最终用户提供了三个选项:

The LogManager class determines which log4j config to use in a static block which runs when the class is loaded. There are three options intended for end-users:

  1. 如果您将 log4j.defaultInitOverride 指定为 false,则它根本不会配置 log4j.
  2. 自己手动指定配置文件的路径并覆盖类路径搜索.您可以通过在 java 中使用以下参数直接指定配置文件的位置:

  1. If you specify log4j.defaultInitOverride to false, it will not configure log4j at all.
  2. Specify the path to the configuration file manually yourself and override the classpath search. You can specify the location of the configuration file directly by using the following argument to java:

-Dlog4j.configuration=<属性文件的路径>

在您的测试运行器配置中.

in your test runner configuration.

允许 log4j 在测试期间扫描 log4j 配置文件的类路径.(默认)

Allow log4j to scan the classpath for a log4j config file during your test. (the default)

另请参阅在线文档.

这篇关于我在哪里可以在 JUnit 测试类中配置 log4j?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆