在 JUnit 测试类中哪里配置 log4j?
看看我写的最后一个 JUnit 测试用例,我在类构造函数中调用了 log4j 的 BasicConfigurator.configure() 方法。 这对于仅从 Eclipse 的“作为 JUnit 测试用例运行”命令运行单个类来说效果很好。 但我意识到这是不正确的:我很确定我们的主测试套件从一个进程运行所有这些类,因此 log4j 配置应该发生在更高的地方。
但有时我仍然需要单独运行一个测试用例,在这种情况下我希望配置 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.
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我在 log4j.xml: 中使用系统属性
并开始测试:
I use system properties in log4j.xml:
and start tests with:
您可能需要查看Simple Logging Facade for Java (SLF4J)。 它是一个围绕 Log4j 的外观,不需要像 Log4j 那样进行初始设置调用。 将 Log4j 切换为 Slf4j 也相当容易,因为 API 差异很小。
You may want to look into to Simple Logging Facade for Java (SLF4J). It is a facade that wraps around Log4j that doesn't require an initial setup call like Log4j. It is also fairly easy to switch out Log4j for Slf4j as the API differences are minimal.
LogManager
类确定在 静态块,在类加载时运行。 为最终用户提供了三个选项:log4j.defaultInitOverride
指定为 false,则根本不会配置 log4j。自己手动指定配置文件的路径并覆盖类路径搜索。 您可以使用
java
的以下参数直接指定配置文件的位置:-Dlog4j.configuration=<属性文件路径>
在您的测试运行器配置中。
允许 log4j 在测试期间扫描 log4j 配置文件的类路径。 (默认)
另请参阅在线文档。
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:log4j.defaultInitOverride
to false, it will not configure log4j at all.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=<path to properties file>
in your test runner configuration.
Allow log4j to scan the classpath for a log4j config file during your test. (the default)
See also the online documentation.
我通常只是将 log4j.xml 文件放入 src/test/resources 中,然后让 log4j 自己找到它:不需要任何代码,默认的 log4j 初始化会拾取它。 (无论如何,我通常想将自己的记录器设置为“调试”)
I generally just put a log4j.xml file into src/test/resources and let log4j find it by itself: no code required, the default log4j initialisation will pick it up. (I typically want to set my own loggers to 'DEBUG' anyway)