Landon Kuhn
Landon Kuhn

Reputation: 78511

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.

Upvotes: 23

Views: 18118

Answers (2)

Mike Minicki
Mike Minicki

Reputation: 8476

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

Upvotes: 3

hvgotcodes
hvgotcodes

Reputation: 120318

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...

Upvotes: 19

Related Questions