Learn to use a different Log4j2 configuration file for JUnit tests is a recommended approach. We can apply two ways to configure Log4j2 specific to tests and that is different from the production logging config file.
test/resources
Folder
1. Place log4j2-test.xml in Place the log4j2-test.xml
file in ‘src/test/resources
‘ folder.
By placing a log4j2-test.xml
into this directory will cause it to be used instead of a log4j2.xml
or log4j2.json
that might be present in ‘src/main/resources‘ folder.

2. Load from external locations with ‘log4j.configurationFile‘ Property
Another way to introduce a different log configuration file is – to set log4j.configurationFile
property in @Before
All annotation in any test class.
For example, we can create test specific logging configuration file log4j2-testConfig.xml
and place it in some external folder. Now let use this file in JUnit tests.
import java.net.MalformedURLException; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.junit.BeforeClass; import org.junit.Test; public class HelloWorldTest { private static Logger LOGGER = null; @BeforeClass public static void setLogger() throws MalformedURLException { System.setProperty("log4j.configurationFile","log4j2-testConfig.xml"); LOGGER = LogManager.getLogger(); } @Test public void testOne() { //test code } }
Drop me your questions related to log4j2 configuration for junit tests in the comments section.
Happy Learning !!
Comments