我已经编写了一个代码来截取selenium webdriver中的页面截图。但是我想在每个页面上截取屏幕截图,因为控件从一个页面进展到下一页,而不管测试用例是通过还是失败。随着1页的工作完成,我需要一个截图。谁能帮我?
package com.training.edureka.selenium.module7;
import org.junit.Test;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import java.io.File;
import org.apache.commons.io.FileUtils;
public class screenshotOfAllCases {
WebDriver driver;
@BeforeTest
public void openBrowser() throws InterruptedException
{
System.setProperty("webdriver.chrome.driver","C:/Program Files (x86)/Google/Chrome/Application/chromedriver.exe");
driver = new ChromeDriver();
Thread.sleep(20000);
driver.get("http://newtours.demoaut.com");
}
@Test
public void getScreenshot()
{
try {
File scrFile =
((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new
File("e:\\homepage.png"));
} catch (Exception e) {
e.printStackTrace();
}
}
@AfterTest
public void closeBrowser()
{
driver.close();
}
}
答案 0 :(得分:0)
尝试以下代码 public class ScreenshotUtils实现IInvokedMethodListener {
@Override
public void beforeInvocation(final IInvokedMethod method, final ITestResult testResult) {
if (method.isTestMethod()) {
//Open browser
}
}
@Override
public void afterInvocation(final IInvokedMethod method, final ITestResult testResult) {
if (method.isTestMethod()) {
//Logic to your screenshot taking
//Close browser
}
}
}
答案 1 :(得分:0)
我在导入org.junit.Test中看到使用Junit,在基础测试类中尝试Junit规则:
@Rule
public TestRule testWatcher = new TestWatcher() {
@Override
public void failed(Throwable e, Description test) {
getScreenshot()
@Override
public void succeeded(Description test) {
getScreenshot()
}
};