《Log4j 2 官方文檔》Testing in Maven
在 Maven 中使用測試
Maven在整個構建生命周期內可以運行單元測試和功能測試。默認情況下, 任何在 src/test/resources
路徑下的文件都會複製到 target/test-classes
路徑中, 同時這些文件在執行測試過程中,也會被包含在 classpath
中. 正因為這樣的特性,如果將一個 log4j2-test.xml
文件放到 src/test/resources
目錄中, 這會替換掉當前正在使用的 log4j2.xml
或 log4j2.json
配置。因此, 在測試期間可以使用不同的日誌配置,而不是當前在產品中使用的配置。
第二種方法是: 在測試類方法中使用 @BeforeClass
注解設置 log4j.configurationFile
的屬性,這種方法在 Log4j 2
被大量使用。和第一種方法相比,測試的配置文件可以使用任意文件名。
第三種方法同樣在 Log4j 2
中大量使用, 它使用了 LoggerContextRule JUnit
測試規則, LoggerContextRule
提供額外的便於測試的方法. 另外, 這種方法需要添加 log4j-core test-jar
到 test scope
的依賴中.舉個例子
public class AwesomeTest {
@Rule
public LoggerContextRule init = new LoggerContextRule("MyTestConfig.xml");
@Test
public void testSomeAwesomeFeature() {
final LoggerContext ctx = init.getContext();
final Logger logger = init.getLogger("org.apache.logging.log4j.my.awesome.test.logger");
final Configuration cfg = init.getConfiguration();
final ListAppender app = init.getListAppender("List");
logger.warn("Test message");
final List<LogEvent> events = app.getEvents();
// etc.
}
}
最後更新:2017-05-19 10:31:09