多测师是一家拥有先进的教学理念,强大的师资团队,业内好评甚多的接口自动化测试培训机构!

17727591462

联系电话

您现在所在位置:接口自动化测试培训 > 新闻资讯

selenium运行用例打印日志及错误截图

更新时间:2022-03-11 09:48:50 作者:多测师 浏览:244

  selenium运行自动化用例中,并不支持log和错误截图功能,但是在apache中有一个打印日志的jar包log4j及结合java中的IO来实现这些功能。

  Log4j日志功能

  1.控制日志信息输送的目的地是控制台、文件等;

  2.控制每一条日志的输出格式;

  3.通过定义每一条日志信息的级别,我们能够更加细致地控制日志的生成过程;

  4.最不错的就是,这些可以通过一个配置文件来灵活地进行配置,而不需要修改应用的代码。

  屏幕截图功能

  截图捕获功能可以在用例失败时进行截图,帮助我们更好地分析结果。

selenium运行用例打印日志及错误截图

  log4j.xml代码:

  以下是详细代码:

  package com.autotest.publicmethod;

  import java.io.File;

  import java.io.IOException;

  import java.text.SimpleDateFormat;

  import java.util.Date;

  import org.apache.commons.io.FileUtils;

  import org.apache.log4j.LogManager;

  import org.apache.log4j.Logger;

  import org.apache.log4j.xml.DOMConfigurator;

  import org.openqa.selenium.By;

  import org.openqa.selenium.OutputType;

  import org.openqa.selenium.TakesScreenshot;

  import org.openqa.selenium.WebDriver;

  import org.openqa.selenium.WebElement;

  import com.autotest.businesskeyword.BrowserDriver;

  public class JavaEncapsulationMethod {

  private static WebElement element = null;

  public static String getCurrentSystemTime(){

  Date now = new Date();

  SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");

  String time = dateFormat.format( now );

  return time;

  }

  public static void errorScreenshot(WebDriver driver,String path,String pictureFormat) throws IOException{

  String systemTime = JavaEncapsulationMethod.getCurrentSystemTime();

  String pictureName = systemTime + pictureFormat ;

  File jpg = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);

  FileUtils.copyFile(jpg, new File(path + pictureName));

  }

  public static WebElement elementException(WebDriver driver,By by,String elementName,String className) throws Exception{

  Logger log = LogManager.getLogger(className);

  DOMConfigurator.configure("log4j.xml");

  try{

  element = driver.findElement(by);

  element.isDisplayed();

  log.info(elementName+"元素存在");

  return element;

  }

  catch(Exception e){

  log.error(elementName+"元素不存在,浏览器关闭,请查看截图并查找原因");

  JavaEncapsulationMethod.errorScreenshot(driver, "E:/workspace/Automation/errorPictrue/", ".jpg");

  BrowserDriver.closeBrowser(driver);

  throw(e);

  }

  }

  }

  以上内容为大家介绍了selenium运行用例打印日志及错误截图,本文由多测师亲自撰写,希望对大家有所帮助。了解更多自动化测试相关知识:https://www.aichudan.com/xwzx/

联系电话

17727591462

返回顶部