简体   繁体   中英

How to configure log4j in a unit testing environment?

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.

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.

So I recommend creating a class that is your BaseTestCase and doing that in there.

Note, having some sort of test-resources with the relevant configuration is not a bad idea...

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:

http://robertmaldon.blogspot.com/2007/09/programmatically-configuring-log4j-and.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM