selenium(java)利用testng监听test运行失败时截图

目录如下所示
selenium(java)利用testng监听test运行失败时截图_第1张图片
TestIms 类中有两个测试方法
@Listeners({TestngListenerScreenshot.class})
public class TestIms extends baseDriver{

	@Test
//打开首页
public void openPage(){
	//System.setProperty("webdriver.chrom.driver", "D:\\chromedriver.exe");
	//driver = new ChromeDriver();
	driver.get("http:xxxxxxxxxxxxxxx);
	waitTime(2000);
	driver.manage().window().maximize();
	waitTime(2000);
}

@Test(dependsOnMethods={"openPage"})
//账号登录
public void Login(){
	this.propertiesfile();
	WebElement name = driver.findElement(By.id(prop.getProperty("user")));
	name.sendKeys(prop.getProperty("uservalue"));
	waitTime(1000);
	WebElement passwo = driver.findElement(By.id(prop.getProperty("passwo")));
	passwo.sendKeys(prop.getProperty("passwovalue"));
	waitTime(1000);
	WebElement Loginbutton = driver.findElement(By.id(prop.getProperty("login")));
	Loginbutton.click();
	waitTime(3000);	
	String e1 = driver.findElement(By.id("login-name")).getText();
	System.out.println("当前登录人是: "+e1);
}
//时间等待
public static void waitTime(int time){
	try {
		Thread.sleep(time);
	} catch (InterruptedException e) {
		e.printStackTrace();
	}
}

}

配置文件TestData.properties中的内容
user=myname
uservalue=20190408
passwo=password
passwovalue=zjjc123456
login=login

baseDriver类是一个基类,实现WebDriver提供和properties文件的加载以供读取调用,代码如下:

public class baseDriver {

public WebDriver driver;
Properties prop = new Properties();
public baseDriver(){
	System.setProperty("webdriver.chrom.driver", "D:\\chromedriver.exe");
	driver = new ChromeDriver();
}

//加载properties文件
	public void propertiesfile(){
		try {
			prop.load(TestIms.class.getResourceAsStream("TestData.properties"));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}		
//截图操作
	public void takeScreenShot(){
		long date = System.currentTimeMillis();
		String path = String.valueOf(date);
		//获取系统的当前路径
		String curPath = System.getProperty("user.dir");
		path = path+".png";
		String screenPath = curPath+"/"+path;
		File screen = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
		try {
			FileUtils.copyFile(screen, new File(screenPath));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
TestngListenerScreenshot中覆盖源码中的运行失败时才截图的方法
public class TestngListenerScreenshot extends TestListenerAdapter {

@Override
public void onTestSuccess(ITestResult tr) {
	super.onTestSuccess(tr);
  }
@Override
  public void onTestFailure(ITestResult tr) {
	super.onTestFailure(tr);
	TakeScreenShot(tr);
  }

private void TakeScreenShot(ITestResult tr){
	baseDriver b = (baseDriver) tr.getInstance();
	b.takeScreenShot();
}
	
 @Override
  public void onTestSkipped(ITestResult tr) {
	 super.onTestSkipped(tr);
  }
 @Override
  public void onStart(ITestContext testContext) {
	 super.onStart(testContext);
  }
 @Override
  public void onFinish(ITestContext testContext) {
	 super.onFinish(testContext);
  }	

}
testng.xml文件中增加监听。代码如下;
在这里插入图片描述

你可能感兴趣的:(软件测试,selenium,性能测试,jmeter,Java)