一, 异常截图场景
二, 实现原理
import io.qameta.allure.Allure;
import org.apache.commons.io.FileUtils;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.time.Duration;
import java.util.Date;
import static java.lang.Thread.sleep;
import static org.junit.jupiter.api.Assertions.fail;
public class ScreenTest {
private static WebDriver driver;
@BeforeAll
static void setupClass(){
ChromeOptions options = new ChromeOptions();
options.addArguments("--remote-allow-origins=*");
driver = new ChromeDriver(options);
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(3));
}
@AfterAll
static void tearDownClass() throws InterruptedException {
sleep(5000);
driver.quit();
}
void saveScreen() throws IOException {
//生成时间戳字符串(时间戳太长会报错)
Date date = new Date();
long timestamp = date.getTime()/1000;
//将截图文件保存
File scfile = new File("./files/" + timestamp + ".png");
File currentScreen = ((TakesScreenshot) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(currentScreen, scfile);
//添加到报告附件
Allure.addAttachment("add_pic","image/png",new FileInputStream(scfile),".png");
}
@Test
void screenTest() throws IOException {
try{
driver.get("https://ceshiren.com/");
// 错误代码
driver.findElement(By.name("adb"));
}catch (Exception e){
saveScreen();
fail("NoSuchElementException" + e);
}
}
}