java 如何在单元测试环境中配置log4j?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4673853/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to configure log4j in a unit testing environment?
提问by Landon Kuhn
What is the best way to configure log4j for use in a unit testing environment? I prefer my unit tests to have no external dependencies, so reading the log4j configuration file is not an option. Ideally there would be 1 or 2 function calls I could make from within the unit test setup function.
在单元测试环境中配置 log4j 的最佳方法是什么?我更喜欢我的单元测试没有外部依赖,所以读取 log4j 配置文件不是一个选项。理想情况下,我可以在单元测试设置函数中进行 1 或 2 个函数调用。
回答by hvgotcodes
you could put a static code block at the top of the test that does
你可以在测试的顶部放置一个静态代码块
BasicConfigurator.configure();
Note that the problem with this is that every time that line is executed, log4j will add an appender and you will get duplicate log statements. So if you do that in every test class, you will end up with n duplicates of every log statement.
请注意,这样做的问题是每次执行该行时,log4j 都会添加一个 appender,您将获得重复的日志语句。所以如果你在每个测试类中都这样做,你最终会得到每个日志语句的 n 个重复。
So I recommend creating a class that is your BaseTestCase and doing that in there.
所以我建议创建一个类作为你的 BaseTestCase 并在那里做。
Note, having some sort of test-resources with the relevant configuration is not a bad idea...
请注意,拥有某种具有相关配置的测试资源并不是一个坏主意......
回答by Mike Minicki
Log4j is already an external dependency. But anyway, you got your answer below (hvgotcodes), so I'll just add that you can set up log4j programatically. Basically everything you can do via config, you can do by code as well:
Log4j 已经是一个外部依赖。但是无论如何,您在下面得到了答案(hvgotcodes),所以我将补充一点,您可以以编程方式设置 log4j。基本上你可以通过配置做的一切,你也可以通过代码来做:
http://robertmaldon.blogspot.com/2007/09/programmatically-configuring-log4j-and.html
http://robertmaldon.blogspot.com/2007/09/programmatically-configuring-log4j-and.html