使用Log4j在测试过程中打印执行日志
1、创建log4j.xml配置文件
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"debug="false"> <appender name="fileAppender" class="org.apache.log4j.FileAppender"> <param name="Threshold" value="INFO"/> <param name="file" value="logfile.log"/> <layout class="org.apache.log4j.PatternLayout"> <param name="ConversionPattern" value="%d %-5p [%c{1}] %m %n"/> </layout>> </appender> <root> <level value="INFO"/> <appender-ref ref="fileAppender"/> </root> </log4j:configuration>
2、编写工具类代码
package china; import org.apache.log4j.Logger; public class log { private static Logger Log=Logger.getLogger(log.class.getName()); public static void startTestCase(String sTestCaseName){ Log.info("-------------------------------------------"); Log.info("*************"+sTestCaseName+"*************"); } public static void endTestCase(String sTestCaseName){ Log.info("****************测试用例执行结束****************"); Log.info("-------------------------------------------"); } public static void info(String message){ Log.info(message); } public static void warn(String message){ Log.info(message); } public static void error(String message){ Log.info(message); } public static void fatal(String message){ Log.info(message); } public static void debug(String message){ Log.info(message); } }
3、编写测试类代码
package china; import org.testng.annotations.Test; import org.testng.annotations.BeforeMethod; import org.apache.log4j.xml.DOMConfigurator; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeClass; public class testLog4j { public WebDriver driver; String baseUrl="http://www.sogou.com"; @Test public void f() { log.startTestCase("搜索"); driver.get(baseUrl); log.info("打开sogou首页"); driver.findElement(By.id("query")).sendKeys("自动化测试"); log.info("输入搜索关键字“自动化测试”"); driver.findElement(By.id("stb")).click(); log.info("单机搜索按钮"); log.endTestCase("搜索"); } @BeforeMethod public void beforeMethod() { System.setProperty("webdriver.chrome.driver", "C:\\chromedriver\\chromedriver.exe"); driver=new ChromeDriver(); } @AfterMethod public void afterMethod() { driver.quit(); } @BeforeClass public void beforeClass() { DOMConfigurator.configure("log4j.xml"); } }
时间: 2024-10-06 01:44:45