selenium+testng+allure测试报告及失败截图
导入依赖
<properties>
<maven.compiler.source>8</maven.compiler.source>
<maven.compiler.target>8</maven.compiler.target>
<project.build.sourceEncoding>GBK</project.build.sourceEncoding>
<aspectj.version>1.9.7</aspectj.version>
</properties>
<dependencies>
<dependency>
<groupId>org.seleniumhq.selenium</groupId>
<artifactId>selenium-java</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-testng</artifactId>
<version>2.18.1</version>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<version>6.14.3</version>
</dependency>
<dependency>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-testng</artifactId>
<version>2.18.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
<configuration>
<testFailureIgnore>true</testFailureIgnore>
<argLine>
-javaagent:"${settings.localRepository}/org/aspectj/aspectjweaver/${aspectj.version}/aspectjweaver-${aspectj.version}.jar"
</argLine>
<systemProperties>
<property>
<name>allure.results.directory</name>
<value>${project.build.directory}/allure-results</value>
</property>
</systemProperties>
</configuration>
<dependencies>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>io.qameta.allure</groupId>
<artifactId>allure-maven</artifactId>
<version>2.10.0</version>
</plugin>
</plugins>
</build>
编写监听类
- 截图核心方法byte[] screenshotAs = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
- 注意要使用返回byte[]类型(OutputType.BYTES),一开始我用的OutputType.FILES,结果报告中没有图片
public class TestListener extends TestListenerAdapter {
private final static Logger log = LoggerFactory.getLogger(TrustDomainConfigPage.class);
@Override
public void onStart(ITestContext iTestContext) {
super.onStart( iTestContext );
log.info( String.format( "====================%s测试开始====================", iTestContext.getName() ) );
}
@Override
public void onTestStart(ITestResult iTestResult) {
super.onTestStart( iTestResult );
log.info( String.format( "========%s.%s测试开始========", iTestResult.getInstanceName(), iTestResult.getName()) );
}
@Override
public void onTestSuccess(ITestResult iTestResult) {
super.onTestSuccess( iTestResult );
log.info( String.format( "========%s.%s测试通过========", iTestResult.getInstanceName(), iTestResult.getName()) );
}
@Override
public void onTestFailure(ITestResult iTestResult) {
super.onTestFailure( iTestResult );
BaseTest bt = (BaseTest) iTestResult.getInstance();
WebDriver driver = bt.getDriver();
log.error( String.format( "========%s.%s测试失败,失败原因如下:\n%s========", iTestResult.getInstanceName(), iTestResult.getName(), iTestResult.getThrowable() ));
// 失败截图
takePhoto(driver);
// ScreenShot.takeScreenShot( driver,iTestResult);
}
@Override
public void onTestSkipped(ITestResult iTestResult) {
super.onTestSkipped( iTestResult );
log.info( String.format( "========%s.%s跳过测试========", iTestResult.getInstanceName(), iTestResult.getName()) );
}
@Override
public void onFinish(ITestContext iTestContext) {
super.onFinish( iTestContext );
log.info( String.format( "====================%s测试结束====================", iTestContext.getName() ) );
}
@Attachment(value = "失败截图如下:",type = "image/png")
public byte[] takePhoto(WebDriver driver){
byte[] screenshotAs = ((TakesScreenshot)driver).getScreenshotAs(OutputType.BYTES);
return screenshotAs;
}
}
编写测试基类
- 在测试基类上添加注解@Listeners({TestListener.class}),括号中的类名字为监听类的类名,由于所有测试类都集成该类,所以只在此类上加@Listeners注解即可。
@Listeners({TestListener.class})
public class BaseTest {
public static UseBrowser useBrowser = new UseBrowser();
public static WebDriver driver;
public static WebDriver getDriver(){
return driver;
}
@BeforeSuite
public void start() throws Exception {
Map<String, String> map = Utils.parseProperties();
String ip = map.get("ServerIP");
try {
driver = useBrowser.startChrome("https://" + ip + ":8443/webui/index.jsp");
// driver = useBrowser.startIE(URL);
// driver = useBrowser.startFirefox(URL)
} catch (Exception e) {
System.out.println(e);
}
}
@AfterSuite
public void end() throws Exception {
useBrowser.tearDownBrowser();
}
}
UseBrowser为启动浏览器的类
- 启动浏览器,设置启动参数、下载文件地址
public class UseBrowser {
Logger log = LoggerFactory.getLogger(UseBrowser.class);
// 谷歌driver在disk中的相对路径
public static String CHROME_DRIVER_PATH = ClassLoader.getSystemResource("webdriver/chromedriver.exe").getPath();
// 火狐driver在disk中的相对路径
public static String FIREFOX_DRIVER_PATH = ClassLoader.getSystemResource("webdriver/geckodriver.exe").getPath();
// IEdriver在disk中的相对路径
public static String IE_DRIVER_PATH = ClassLoader.getSystemResource("webdriver/IEDriverServer.exe").getPath();
private static final Duration TIME_OUT_IN_SECONDS = Duration.ofSeconds(10); //超时时间(单位秒)
static final String chromeDriverKey = "webdriver.chrome.driver";
static final String firefoxDriverKey = "webdriver.firefox.driver";
static final String ieDriverKey = "webdriver.ie.driver";
public static WebDriver driver;
//启动谷歌浏览器
public WebDriver startChrome(String url){
try {
System.setProperty(chromeDriverKey, CHROME_DRIVER_PATH);
ChromeOptions options = setChromeDownload();
driver = new ChromeDriver(options);
driver.get(url);
log.info("open chrome success ! ");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(TIME_OUT_IN_SECONDS);
} catch (Exception e) {
log.error("打开谷歌浏览器时出错了"+e);
}
return driver;
}
/**
* 打开火狐
* @param url
* @return
*/
public WebDriver startFireFox(String url){
try {
System.setProperty(firefoxDriverKey, FIREFOX_DRIVER_PATH);
driver = new FirefoxDriver();
driver.get(url);
log.info("open firefox success ! ");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(TIME_OUT_IN_SECONDS);
} catch (Exception e) {
log.error("打开火狐浏览器时出错了"+e);
}
return driver;
}
/**
* 打开ie
* @param url
* @return
*/
public WebDriver startIE(String url){
try {
System.setProperty(ieDriverKey, IE_DRIVER_PATH);
driver = new InternetExplorerDriver();
driver.get(url);
log.info("open IE success ! ");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(TIME_OUT_IN_SECONDS);
}catch (Exception e){
log.error("打开ie浏览器时出错了"+e);
}
return driver;
}
//关闭浏览器
public void tearDownBrowser(){
try {
Thread.sleep(5000);
driver.quit();
log.info("成功关闭浏览器!");
} catch (Exception e) {
log.error("关闭浏览器时出错了"+e);
}
}
/**
* 谷歌浏览器下载设置
* @return
*/
public ChromeOptions setChromeDownload(){
//设置下载路径
String parentPath = new File(System.getProperty("user.dir")).getParent();
String downloadPath = parentPath+File.separator+"data"+File.separator+"download";
File folder = new File(downloadPath);
if (!folder.exists() && !folder.isDirectory()) {
folder.mkdirs();
}
ChromeOptions options = new ChromeOptions();
//忽略访问地址不安全
options.addArguments("ignore-certificate-errors");
options.addArguments("--no-sandbox");
options.addArguments("--disable-dev-shm-usage");
HashMap<String, Object> chromePrefs = new HashMap<>();
chromePrefs.put("profile.default_content_settings.popups", 0);
//下载文件不再询问是否保留
chromePrefs.put("safebrowsing.enabled", true);
chromePrefs.put("download.default_directory", downloadPath);
chromePrefs.put("download.prompt_for_download", false);
chromePrefs.put("download.directory_upgrade", true);
options.setExperimentalOption("prefs",chromePrefs);
return options;
}
编写测试类
- 继承BaseTest,获得BaseTest的WebDriver直接使用
public class TestTrustDomainConfig extends BaseTest {
@BeforeClass
public void testTrustDomain_into(){
// LoginPage.login(driver, "sys", "inf0sec312!");
TrustDomainConfigPage.getIntoTrustPage(driver);
}
/**
* 上传根证
* @param name
* @param path
*/
@Test(description = "上传根证", dataProviderClass = TrustDataProvider.class, dataProvider = "filedName-path")
public void testTrustDomain_01(String name, String path){
TrustDomainConfigPage.uploadRootCer(driver, name, path, "添加信任域成功");
}
/**
* 不传文件点击添加按钮
*/
@Test(description = "不传文件点击添加按钮")
public void testTrustDomain_02(){
WebUI.click(driver, TrustDomainConfigLocator.addOrSaveButton);
WebUI.checkAlertText(driver, "请输入信任域名称!");
}
}
testng.xml
- 在类上加了监听类注解,testng.xml中不用再加监听类
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite name="Suite">
<test thread-count="1" name="Test" parallel="classes">
<classes>
<class name="testcase.login.TestLogin"/>
<class name="testcase.servicemanage.trustconfig.TestTrustDomainConfig"></class>
</classes>
</test>
</suite>
报告
-
第一种:用例执行完会在根目录下生成allure-results文件夹,存放的是json格式测试结果,我们需执行命令生成报告,这里举例一种生成方法,在本地项目目录allure-results外面执行命令:
//生成报告前先清空已有的报告 allure generate allure-results -o report --clean //打开本地报告,必须用命令打开,直接打开html看不到数据 allure open report
也可直接在IDEA的终端中执行生成报告,同上执行generate命令,执行成功后同级目录下产生report,在IDEA中直接打开index.html即可