Estrutura do modelo de objeto de página completa -2021

Neste tutorial, aprenderemos sobre o Modelo de Objeto de Página e também projetaremos e desenvolveremos a estrutura do Modelo de Objeto de Página do zero. 

Havíamos discutido todos os tipos de estrutura no Selenium, incluindo o modelo de objeto de página , aqui iríamos em detalhes.

Vamos projetar e desenvolver os recursos abaixo.

O que é o design do Page Object Model Framework no Selenium  

Modelo de objeto de página é um Modelo de Design para a construção de Automação de teste do Selenium, onde distribuímos todo o nosso Aplicativo em teste em pequenas páginas (às vezes uma página da Web é considerada uma página e às vezes uma subparte de uma página da Web também é considerada uma Página ). Cada uma dessas páginas é representada como uma classe Java, e as funcionalidades das páginas são escritas como métodos diferentes na classe Java da respectiva página.

Digamos que você tenha um aplicativo do Gmail que irá automatizar; portanto, a página de login do Gmail está lá, onde você tem poucas funcionalidades importantes, como login, criar uma conta, etc.

Aqui, criaremos uma classe java como GmailLoginPage e escreveremos métodos nomeados como performLogin (), createUserAccount, etc. 

Digamos que uma vez que você esteja logado em sua conta do Gmail, você tem muitos recursos como caixa de entrada, itens enviados, lixo, etc. Agora aqui, para cada módulo, você cria uma classe Java e mantém suas funcionalidades como métodos Java dentro das respectivas classes java. 

Por que o modelo de objeto de página

O Modelo de Objeto de Página é um modelo de design de estrutura muito robusto e avançado onde você pode cuidar das áreas abaixo: 

Estrutura da estrutura do modelo de objeto de página híbrida

Na série tutorial anterior, entendemos o modelo de objeto de página híbrido, e agora vamos projetar e desenvolver uma estrutura.

A arquitetura da estrutura do Modelo de Objeto de Página

Podemos simplesmente criar um projeto maven e incorporar as dependências no arquivo POM.xml que são necessárias para a estrutura inicialmente parecida com esta: 

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
\txsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
\t<modelVersion>4.0.0</modelVersion>

\t<groupId>demo</groupId>
\t<artifactId>DemoAutomation</artifactId>
\t<version>0.0.1-SNAPSHOT</version>
\t<packaging>jar</packaging>

\t<name>DemoAutomation</name>
\t<url>http://maven.apache.org</url>
\t<properties>
\t\t<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
\t</properties>
\t<build>
\t\t<plugins>
\t\t\t<plugin>
\t\t\t\t<groupId>org.apache.maven.plugins</groupId>
\t\t\t\t<artifactId>maven-compiler-plugin</artifactId>
\t\t\t\t<version>3.0</version>
\t\t\t\t<configuration>
\t\t\t\t\t<source>7</source>
\t\t\t\t\t<target>7</target>
\t\t\t\t</configuration>
\t\t\t</plugin>
\t\t\t<plugin>
\t\t\t\t<groupId>org.apache.maven.plugins</groupId>
\t\t\t\t<artifactId>maven-surefire-plugin</artifactId>
\t\t\t\t<version>2.4.2</version>
\t\t\t\t<configuration>
\t\t\t\t\t<suiteXmlFiles>
\t\t\t\t\t\t<suiteXmlFile>testNg.xml</suiteXmlFile>
\t\t\t\t\t</suiteXmlFiles>
\t\t\t\t</configuration>
\t\t\t</plugin>
\t\t</plugins>
\t</build>
\t<reporting>
\t\t<plugins>
\t\t\t<plugin>
\t\t\t\t<groupId>org.reportyng</groupId>
\t\t\t\t<artifactId>reporty-ng</artifactId>
\t\t\t\t<version>1.2</version>
\t\t\t\t<configuration>
\t\t\t\t    <outputdir>/target/testng-xslt-report</outputdir>
\t\t\t\t    <sorttestcaselinks>true</sorttestcaselinks>
\t\t\t            <testdetailsfilter>FAIL,SKIP,PASS,CONF,BY_CLASS</testdetailsfilter>
\t\t\t\t    <showruntimetotals>true</showruntimetotals>
\t\t\t\t</configuration>
\t\t\t</plugin>
\t\t</plugins>
\t</reporting>
\t<dependencies>
\t\t<dependency>
\t\t\t<groupId>org.seleniumhq.selenium</groupId>
\t\t\t<artifactId>selenium-server</artifactId>
\t\t\t<version>2.53.0</version>
\t\t</dependency>
\t\t<dependency>
\t\t\t<groupId>org.testng</groupId>
\t\t\t<artifactId>testng</artifactId>
\t\t\t<version>6.8.1</version>
\t\t</dependency>
\t\t<dependency>
\t\t\t<groupId>org.apache.poi</groupId>
\t\t\t<artifactId>poi</artifactId>
\t\t\t<version>3.8</version>
\t\t</dependency>
\t\t<dependency>
\t\t\t<groupId>org.apache.poi</groupId>
\t\t\t<artifactId>poi-ooxml</artifactId>
\t\t\t<version>3.8</version>
\t\t</dependency>

\t\t<dependency>
\t\t\t<groupId>com.googlecode.json-simple</groupId>
\t\t\t<artifactId>json-simple</artifactId>
\t\t\t<version>1.1</version>
\t\t</dependency>

\t\t<dependency>
\t\t\t<groupId>net.sourceforge.jexcelapi</groupId>
\t\t\t<artifactId>jxl</artifactId>
\t\t\t<version>2.6</version>
\t\t</dependency>
\t</dependencies>
</project>

Depois disso, construiremos pequenos módulos e utilitários, aos quais anexamos este instantâneo abaixo apenas para fornecer uma visão / visão de alto nível. Vamos construir utilitários um por um. 

Aqui estão os módulos abaixo que iremos desenvolver; fornecemos o snippet de código para o mesmo: 

DriverUtils - Estrutura de modelo de objeto de página

Este módulo fornece todos os utilitários e suporte para trabalhar com os vários navegadores (Chrome, Firefox, etc.). Este utilitário é baseado no Factory padrão de design, como discutimos no tutorial anterior aqui.

pacote com.base.driverUtils; importar org.openqa.selenium.WebDriver; public interface IDriver { public WebDriver init(String browserName); }

Implementação de driver local, que será executado localmente com Selenium WebdriverName :

pacote com.base.driverUtils;
importar org.openqa.selenium.WebDriver;
importar org.openqa.selenium.chrome.ChromeDriver;
importar org.openqa.selenium.firefox.FirefoxDriver;
importar org.openqa.selenium.ie.InternetExplorerDriver;
classe pública LocalDriver implementa IDriver {
  public WebDriver init(String nomeDoNavegador) {
     switch (nomedonavegador) {
     caso "firefox":
        retornar novo FirefoxDriver();
     caso "cromo":
        System.setProperty("webdriver.chrome.driver",
              "..\\\\DummyAutomation\\\\DriverExe\\\\chromedriver.exe");
        retornar novo ChromeDriver();
     caso "ou seja":
        System.setProperty("webdriver.ie.driver",
              "..\\\\DummyAutomation\\\\DriverExe\\\\IEDriverServer.exe");
        retornar novo InternetExplorerDriver();
     padrão:
        retornar novo FirefoxDriver();
     }
  }
}

Webdriver remoto: para trabalhar com um webdriver remoto (como Selenium Grid), você precisa de uma referência remota do driver do navegador, que funciona como: 

pacote com.base.driverUtils; import java.net.MalformedURLException; importar java.net.URL; importar org.openqa.selenium.WebDriver; importar org.openqa.selenium.remote.DesiredCapabilities; importar org.openqa.selenium.remote.RemoteWebDriver; classe pública RemoteDriver implementa IDriver { Caps DesiredCapabilities; String remoteHuburl; @Override public WebDriver init(String browserName) { switch (browserName) { case "firefox": tente { return new RemoteWebDriver(new URL(remoteHuburl), caps.firefox()); } catch (MalformedURLException e2) { // TODO bloco catch gerado automaticamente e2.printStackTrace(); } case "chrome": tente { return new RemoteWebDriver(new URL(remoteHuburl), caps.chrome()); } catch (MalformedURLException e1) { // TODO bloco catch gerado automaticamente e1.printStackTrace(); } case "ie": tente { return new RemoteWebDriver(new URL(remoteHuburl), caps.internetExplorer()); } catch (MalformedURLException e) { // TODO bloco catch gerado automaticamente e.printStackTrace(); } default: try { return new RemoteWebDriver(new URL(remoteHuburl), caps.firefox()); } catch (MalformedURLException e) { // TODO bloco catch gerado automaticamente e.printStackTrace(); } } return null; } }

Classe de driver de fábrica: Isso nos fornece o objeto de classe de driver (remoto / local) para iniciar os navegadores de sua escolha. Pegaremos o tipo de driver (local ou remoto) e navegador (cromo ou firefox etc.) por meio do arquivo de configuração (usamos um arquivo de propriedades para manter as configurações, que compartilharemos em breve)

pacote com.base.driverUtils; public class DriverProvider { public IDriver getDriver(String typeOfDriverExecution){ switch(typeOfDriverExecution){ case "local": return new LocalDriver(); case "remoto": retorna novo RemoteDriver(); default : retorna novo LocalDriver(); } } }

Agora, onde quer que você precise da referência do driver, você pode simplesmente criar o objeto do objeto de classe de fábrica (DriverProvider, neste caso) e pode iniciar a instância do navegador do driver.

Aqui está o arquivo de configuração básico; você pode criar um arquivo de propriedades e armazenar os valores como este: 

modeOfExecution=navegador local=chrome url=http://www.applicationUrl.com/

Estrutura do modelo de objeto DataUtils-Page: 

Projetamos os utilitários de dados aqui com o mesmo padrão de design de fábrica que fizemos na implementação dos módulos do navegador do driver.

Aqui está o trecho de código abaixo para o mesmo; na estrutura, mostramos utilitários de Excel e utilitários de propriedades, você pode aprimorar mais para oferecer suporte a outros utilitários de dados como YAML, PDF, etc .: 

A interface aqui vai assim: 

pacote com.base.dataUtils; public interface IDataProvider { public Object[][] fetchDataSet(String... dataFileInfo); public String fetchData(String... dataFileInfo); }

Aqui está a implementação para Provedor de dados Excel

pacote com.base.dataUtils; import java.io.File; importar java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import org.apache.poi.xssf.usermodel.XSSFCell; importar org.apache.poi.xssf.usermodel.XSSFSheet; import org.apache.poi.xssf.usermodel.XSSFWorkbook; public class ExcelDataProvider implementa IDataProvider { FileInputStream fis = null; privada estática XSSFWorkbook workBook = null; Célula XSSFCell estática privada; folha XSSFSheet estática privada; public static String[][] excelDataSet = null; @Override public Object[][] fetchDataSet(String... dataFileInfo) { String excelFilePath = dataFileInfo[0]; String excelSheetName = dataFileInfo[1]; Arquivo arquivo = new Arquivo(excelFilePath); tente { fis = new FileInputStream(arquivo); } catch (FileNotFoundException e) { // TODO bloco catch gerado automaticamente e.printStackTrace(); } tente { workBook = new XSSFWorkbook(fis); } catch (IOException e) { // TODO bloco catch gerado automaticamente e.printStackTrace(); } folha = workBook.getSheet(excelSheetName); int ci, cj; int rowCount = sheet.getLastRowNum(); int totalCols = sheet.getRow(0).getPhysicalNumberOfCells(); excelDataSet = new String[rowCount][totalCols - 1]; c = 0; for (int i = 1; i <= rowCount; i++, ci++) { cj = 0; for (int j = 1; j <= totalCols - 1; j++, cj++) { try { excelDataSet[ci][cj] = getCellData(i, j); } catch (Exception e) { // TODO bloco catch gerado automaticamente e.printStackTrace(); } } } return excelDataSet; } public static String getCellData(int RowNum, int ColNum) lança Exception { try { Cell = sheet.getRow(RowNum).getCell(ColNum); int dataType = Cell.getCellType(); if (dataType == 3) { return ""; } else if (dataType == XSSFCell.CELL_TYPE_NUMERIC) { int i = (int) Cell.getNumericCellValue(); return Integer.toString(i); } else { String CellData = Cell.getStringCellValue(); retornar CellData; } } catch (Exception e) { throw (e); } } @Override public String fetchData(String... dataFileInfo) { // TODO Método gerado automaticamente stub return null; } }

Provedor de dados de propriedades: 

pacote com.base.dataUtils; importar java.io.FileInputStream; import java.io.IOException; importar java.util.Properties; classe pública PropertiesDataProvider implementa IDataProvider { FileInputStream fis=null; @Override public Object[][] fetchDataSet(String... dataFileInfo) { // TODO método gerado automaticamente stub return null; } @Override public String fetchData(String... dataFileInfo) { String dataValue; String pathToFile = dataFileInfo[0]; String chave = dataFileInfo[1]; Propriedades propriedades = new Propriedades(); tente { fis=new FileInputStream(pathToFile); propriedades.load(fis); } catch (IOException e) { // TODO bloco catch gerado automaticamente e.printStackTrace(); } dataValue = propriedades.getProperty(chave); return valordados; } }

A classe de fábrica para estes utilitários de dados

pacote com.base.dataUtils; public class DataHelperProvider { public IDataProvider getDataHelperProvider(String typeOfDataHandler) { switch (typeOfDataHandler) { case "excel": return new ExcelDataProvider(); case "propriedades": retorna novo PropertiesDataProvider(); } return null; } }

Utilitários WebAction -Estrutura do modelo de objeto de página

Nos utilitários, escrevemos todos os utilitários relacionados às suas ações na Web, como (clique, sendkeys, capturas de tela, etc.), e podemos utilizá-los em Métodos de página para executar ações da Web para atingir as funcionalidades da página conforme discutido anteriormente neste tutorial. 

Aqui está o snippet de código para os utilitários WebAction: 

pacote com.base.webActionHelperUtils; import java.util.ArrayList; import java.util.List; importar java.util.concurrent.TimeUnit; import org.openqa.selenium.By; importar org.openqa.selenium.WebDriver; importar org.openqa.selenium.WebElement; importar org.openqa.selenium.support.ui.ExpectedConditions; importar org.openqa.selenium.support.ui.WebDriverWait; public class WebActionsHelperUtils { driver WebDriver protegido; public WebActionsHelperUtils(driver WebDriver) { this.driver = driver; } public void safeClick(Por elemento) { waitForElementToBeClickAble(elemento, 30); driver.findElement(elemento).click(); } lista pública getElements(Por elementos) { return driver.findElements(elementos); } public void waitForWebElementsToBeDisplayed(Por elementos, int timeOuts) { WebDriverWait wait = new WebDriverWait(driver, timeOuts); wait.until(ExpectedConditions.visibilityOfAllElements(getElements(elements))); } public void waitForElementToBeClickAble(Por elemento, int timeOutSeconds) { WebDriverWait waitForElement = new WebDriverWait(driver, timeOutSeconds); waitForElement.until(ExpectedConditions.elementToBeClickable(element)); } public void waitForElementToBeDisplayed(Por elemento, int timeOuts) { WebDriverWait wait = new WebDriverWait(driver, timeOuts); wait.until(ExpectedConditions.visibilityOfElementLocated(element)); } public void enterTextIntoElement(Por elemento, String textToBeEntered) { driver.findElement(element).sendKeys(textToBeEntered); } public String getText(Por elemento) { return driver.findElement(elemento).getText(); } public String getAttribute(Por elemento, atributo String) { return driver.findElement(element).getAttribute(attribute); } public boolean isSelected(Por elemento) { boolean isElementSelected = false; if (driver.findElement(elemento).isSelected() == true) { isElementSelected = true; } return isElementSelected; } public void clearField(Por elemento) { driver.findElement(elemento).clear(); } public void implicitamenteWait(int timeOuts) { driver.manage().timeouts().implicitlyWait(timeOuts, TimeUnit.SECONDS); } public boolean isElementPresent(Por elemento) { try { driver.findElement(elemento); retorne verdadeiro; } catch (Exception e) { return false; } } public void switchToTab(int indexOfTab) { ArrayList tabs = new ArrayList (driver.getWindowHandles()); driver.switchTo().window(tabs.get(indexOfTab)); } }

Utilitários do Módulo de Página - Estrutura do Modelo de Objeto de Página

Como sabemos, temos que criar a classe Page e manter as funcionalidades da página nos métodos da página, então agora vamos criar o Módulo da Página para a estrutura do Modelo de Objeto da Página: 

Cada classe de página novamente estende o WebAction Utils que desenvolvemos agora e implementa as interfaces da página, em que as interfaces da página nada mais são do que interfaces para manter os respectivos elementos / localizadores da Web da página.

Agora, por que precisamos de interfaces para armazenar os localizadores: 

Portanto, usamos interfaces separadas para localizadores de página separados para armazenar conforme essa abordagem; Se resolvermos todas as declarações de problemas acima, que são complexidade de tempo, complexidade de espaço e a base de código limpa e sustentável, como nas interfaces, não precisamos criar objetos para acessar localizadores.

pacote com.base.pageModules; import java.util.List; import org.openqa.selenium.By; importar org.openqa.selenium.WebDriver; importar org.openqa.selenium.WebElement; import com.base.commonUtils.JSonHandler; import com.base.webActionHelperUtils.WebActionsHelperUtils; import com.page.locatorModules.HomePageLocators; public class HomePage estende WebActionsHelperUtils implementa HomePageLocators { JSonHandler jsonHandler = new JSonHandler(); public HomePage(driver WebDriver) { super(driver); this.driver = motorista; } public void enterSearchdataToSearchField(String searchData) { waitForElementToBeClickAble(SEARCH_BOX, 10); enterTextIntoElement(SEARCH_BOX, searchData); } public void navigatToUrl() { driver.get(url); } public void captureSearchSuggestion(String pathToJsonDataStore, String searchData) { List elementos = getElementos(SUGGESTION_BOX); jsonHandler.captureAndWriteJsonData(elementos, pathToJsonDataStore, searchData); } public void genericWait(int timeOuts) { implicitlyWait(timeOuts); } public void clikcOnSelectedElement(String option) { int optionSelection = Integer.parseInt(option); safeClick(By.xpath("//div[@id='s-separator']/following-sibling::div[" + optionSelection + "]")); } }

Da mesma forma, você pode continuar incluindo os recursos da página nos diferentes métodos da página dentro das respectivas classes de página. 

Aqui está como o Interfaces de localizadores de página parece : 

pacote com.page.locatorModules; import org.openqa.selenium.By; public interface HomePageLocators { By SEARCH_BOX=By.id("twotabsearchtextbox"); Por SUGGESTION_BOX=By.xpath("//div[@id='suggestions']/div"); }

Agora, o próximo segmento, você pode criar um baseSetUp ou Basetest onde deseja executar as partes de inicialização / carregamento de dados. Além disso, você pode usar @beforeTest, @beoforeClass métodos na própria classe e usá-los em suas classes de teste.

Configuração básica A aula se parece com: 

pacote com.demo.testS;
importar org.openqa.selenium.WebDriver;
importar org.testng.annotations.DataProvider;
importar com.base.dataUtils.DataHelperProvider;
importar com.base.dataUtils.IDataProvider;
importar com.base.driverUtils.DriverProvider;
classe pública BaseSetUp {
\tpublic WebDriver driver;
\tDriverProvider navegadorProvider = new DriverProvider();
\tDataHelperProvider datahelperProvider = new DataHelperProvider();
\tIDataProvider dataProvider = datahelperProvider.getDataHelperProvider("propriedades");
\tIDataProvider dataProviderExcel = datahelperProvider.getDataHelperProvider("excel");
\tpublic final String configProperties = "..\\\\DummyAutomation\\\\TestConfigsData\\\\config.properties";
\tpublic String url = dataProvider.fetchData(configProperties, "url");
\tString modeOfExecution = dataProvider.fetchData(configProperties, "modeOfExecution");
\tString nomedonavegador = dataProvider.fetchData(configProperties, "navegador");
\tString pathToJasonDataStore = "..\\\\DummyAutomation\\\\ProductJsonData\\\\";
\tString pathToExcelData = "..\\\\DummyAutomation\\\\TestConfigsData\\\\TestData.xlsx";
\tpublic WebDriver getDriver() {
\t\treturn driver;
\t}
\tprotected void setDriver() {
\t\tdriver = navegadorProvider.getDriver(modeOfExecution).init(browserName);
\t}
\t@DataProvider(name = "SearchFunctionality")
\tpublic Object[][] getCityDetails() {
\t\tObject[][] arrayObject = dataProviderExcel.fetchDataSet(pathToExcelData, "DataFeed");
\t\treturn arrayObject;
\t}
}

Classes de teste: Como usaríamos TestNG aqui, você precisa escrever o método @test para o script de teste a ser desenvolvido, como: 

Aqui está o trecho de código para as classes de teste  

pacote com.demo.testS; importar org.testng.annotations.AfterMethod; import org.testng.annotations.BeforeMethod; importar org.testng.annotations.Test; import com.base.pageModules.HomePage; import com.base.pageModules.SearchPage; public class DemoTest estende BaseSetUp { HomePage homePage; SearchPage searchPage; @BeforeMethod public void setUpTest() { setDriver(); homePage = new HomePage(driver); searchPage = new SearchPage(driver); homePage.navigatToUrl(); } @Test(dataProvider = "SearchFunctionality") public void search(String searchData, String selectOption) { homePage.enterSearchdataToSearchField(searchData); homePage.genericWait(5); homePage.captureSearchSuggestion(pathToJasonDataStore, searchData); homePage.clikcOnSelectedElement(selectOption); searchPage.clickOnFirstProduct(); searchPage.switchToProductSpecificPage(); searchPage.captureProductData(pathToJasonDataStore, searchData); } @AfterMethod public void tearDown() { if (driver != null) { driver.quit(); } } }

Arquivo TestNgXML -Page Object Model Framework

Você precisaria definir uma classe XML para o testng.xml, que basicamente é uma estrutura de teste de unidade e controla o fluxo de sua automação; você pode mencionar as próprias classes de teste lá.







Assim, com essas atividades, seu básico Modelo de objeto de página a estrutura deve estar pronta agora. Se você deseja alcançar a versão avançada de sua estrutura, pode incorporar as seguintes áreas: 

Report Feature-Page Object Model Framework

Você pode usar qualquer recurso de relatório disponível, como fascinação, relatório de extensão, relatório TestNG ou relatório antecipado usando Pilha ELK, etc. 

Apenas para manter a simplicidade, estamos mostrando aqui o recurso de relatório com o relatório Extent, que possui muitos recursos junto com ele e pode ser considerado um nível intermediário de relatório. 

Você deve construir uma classe para que os utilitários funcionem com o relatório Extent e, ao fazer isso, você deve implementar o interface ITestlistener de TestNg; o código abaixo mostra como: 

package com.cyborg.core.generic.reportUtils;
import com.aventstack.extentreports.ExtentReports;
import com.aventstack.extentreports.ExtentTest;
import com.aventstack.extentreports.Status;
import com.aventstack.extentreports.reporter.ExtentHtmlReporter;
import com.cyborg.core.generic.dataUtils.PropertiesDataUtils;
import io.appium.java_client.android.AndroidDriver;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.Augmenter;
import org.testng.ITestContext;
import org.testng.ITestListener;
import org.testng.ITestResult;
import org.testng.Reporter;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
public class ExtentReportUtils implements ITestListener {
  String screenShotPath = "";
  static ExtentReports extentReports;
  ExtentHtmlReporter extentHtmlReporter;
  protected ExtentTest extentTest;
  static String pathOfFile = "./configurator.properties";
  PropertiesDataUtils propertiesDataUtils = PropertiesDataUtils.getInstance(pathOfFile);
   Boolean log_to_kibana=Boolean.parseBoolean(PropertiesDataUtils.configDataStore.get("log_to_kibana"));
 
   public void setup() {
     try {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH-mm-ss");
        Date now = new Date();
        String currentTime = simpleDateFormat.format(now);
        extentHtmlReporter = new ExtentHtmlReporter(
              new File(System.getProperty("user.dir") + "_Reports_" + currentTime + ".html"));
        extentHtmlReporter.loadXMLConfig(
              new File(System.getProperty("user.dir") + "/src/test/resources/config/extent-config.xml"));
        extentReports = new ExtentReports();
        extentReports.setSystemInfo("Environment", PropertiesDataUtils.configDataStore.get("Environment"));
        extentReports.setSystemInfo("AppName", PropertiesDataUtils.configDataStore.get("AppName"));
        extentReports.setSystemInfo("ModeOfExecution", PropertiesDataUtils.configDataStore.get("modeOfExecution"));
        extentReports.attachReporter(extentHtmlReporter);
        System.out.println("DONE SETUP FOR extent Report");
     } catch (Exception ex) {
        ex.printStackTrace();
     }
  }
  public void setup(String reportName) {
     extentReports = getExtent(reportName);
  }
  public ExtentReports getExtent(String reportName) {
     if (extentReports != null)
        return extentReports; // avoid creating new instance of html file
     extentReports = new ExtentReports();
     extentReports.attachReporter(getHtmlReporter(reportName));
     return extentReports;
  }
  private ExtentHtmlReporter getHtmlReporter(String reportName) {
     extentHtmlReporter = new ExtentHtmlReporter("./reports/" + reportName + ".html");
     extentHtmlReporter.loadXMLConfig("./src/test/resources/config/extent-config.xml");
     // make the charts visible on report open
     extentHtmlReporter.config().setChartVisibilityOnOpen(true);
     extentHtmlReporter.config().setDocumentTitle(PropertiesDataUtils.configDataStore.get("AppName"));
     extentHtmlReporter.config().setReportName("Regression Cycle");
     // Append the existing report
     extentHtmlReporter.setAppendExisting(false);
     Locale.setDefault(Locale.ENGLISH);
     return extentHtmlReporter;
  }
  public void registerTestMethod(Method method) {
     String testName = method.getName();
     extentTest = extentReports.createTest(testName);
  }
  public void sequenceScreenShot(AndroidDriver driver, String application, String step) {
     try {
        extentTest.addScreenCaptureFromPath(screenshotStepWise(driver, application, step));
     } catch (Exception e) {
        e.printStackTrace();
     }
  }
  public void screenshotAnyCase(ITestResult result, WebDriver driver, String application) {
     String testName = result.getName();
     File file = new File(".");
     String filename = testName + ".png";
     String filepath = null;
     try {
        filepath = file.getCanonicalPath() + "/ScreenShots/" + application + "/" + putLogDate() + filename;
     } catch (IOException e1) {
        e1.printStackTrace();
     }
     if (PropertiesDataUtils.configDataStore.get("run_on_jenkins").equalsIgnoreCase("true"))
        screenShotPath = "job/Cyborg2/" + PropertiesDataUtils.configDataStore.get("build_number")
              + "/artifact/ScreenShots/" + application + "/" + putLogDate() + filename;
     else
        screenShotPath = System.getProperty("user.dir") + "/ScreenShots/" + application + "/" + putLogDate()
              + filename;
     try {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshotFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screenshotFile, new File(filepath));
        File reportFile = new File(filepath);
        reportLogScreenshot(reportFile, filename, application);
     } catch (Exception e) {
        Reporter.log("Unable to get the screenshot");
     }
  }
  public String screenshotStepWise(WebDriver driver, String application, String step) throws Exception {
     File file = new File(".");
     String filename = step + ".png";
     String filepath = null;
     try {
        filepath = file.getCanonicalPath() + "/ScreenShots/" + application + "/" + putLogDateWithoutmm() + filename;
     } catch (IOException e1) {
        e1.printStackTrace();
     }
     if (PropertiesDataUtils.configDataStore.get("run_on_jenkins").equalsIgnoreCase("true"))
        screenShotPath = "job/Cyborg2/" + PropertiesDataUtils.configDataStore.get("build_number")
              + "/artifact/ScreenShots/" + application + "/" + putLogDateWithoutmm() + filename;
     else
        screenShotPath = System.getProperty("user.dir") + "/ScreenShots/" + application + "/"
              + putLogDateWithoutmm() + filename;
     try {
        WebDriver augmentedDriver = new Augmenter().augment(driver);
        File screenshotFile = ((TakesScreenshot) augmentedDriver).getScreenshotAs(OutputType.FILE);
        FileUtils.copyFile(screenshotFile, new File(filepath));
     } catch (Exception e) {
        Reporter.log("Unable to get the screenshot");
     }
     return screenShotPath;
  }
  protected void reportLogScreenshot(File file, String fileName, String application) {
     System.setProperty("org.uncommons.reportng.escape-output", "false");
     String absolute = file.getAbsolutePath();
     if (PropertiesDataUtils.configDataStore.get("run_on_jenkins").equalsIgnoreCase("true"))
        absolute = " /job/Cyborg2/" + PropertiesDataUtils.configDataStore.get("build_number")
              + "/artifact/ScreenShots/" + application + "/" + putLogDate() + fileName;
     else
        absolute = System.getProperty("user.dir") + "/ScreenShots/" + application + "/" + putLogDate() + fileName;
     screenShotPath = absolute;
  }
  public void captureStatus(ITestResult result) {
     if (result.getStatus() == ITestResult.SUCCESS) {
        extentTest.log(Status.PASS, "The test method Named as :" + result.getName() + " is PASSED");
        try {
           extentTest.addScreenCaptureFromPath(screenShotPath);
        } catch (IOException e) {
           e.printStackTrace();
        }
     } else if (result.getStatus() == ITestResult.FAILURE) {
        extentTest.log(Status.FAIL, "The test method Named as :" + result.getName() + " is FAILED");
        extentTest.log(Status.FAIL, "The failure : " + result.getThrowable());
        extentTest.log(Status.FAIL, "StackTrace: " + result.getThrowable());
        try {
           extentTest.addScreenCaptureFromPath(screenShotPath);
        } catch (IOException e) {
           e.printStackTrace();
        }
     } else if (result.getStatus() == ITestResult.SKIP) {
        extentTest.log(Status.SKIP, "The test method Named as :" + result.getName() + " is SKIPPED");
     }
  }
  public String putLogDate() {
     Calendar c = new GregorianCalendar();
     c.add(Calendar.DATE, +0);
     Date s = c.getTime();
     String dateString = new SimpleDateFormat("_EEE_ddMMMyyyy_hhmm").format(s);
     return dateString;
  }
  public String putLogDateWithoutmm() {
     Calendar c = new GregorianCalendar();
     c.add(Calendar.DATE, +0);
     Date s = c.getTime();
     String dateString = new SimpleDateFormat("_EEE_ddMMMyyyy_hh").format(s);
     return dateString;
  }
  public void cleanup() {
     extentReports.flush();
  }
  public void onTestStart(ITestResult result) {
     /*
      * try { DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH-mm-ss"); Date
      * date = new Date();
      */
     /*
      * record = new ATUTestRecorder(System.getProperty("user.dir")+"/videos",
      * dateFormat.format(date), false); record.start();
      *//*
         *
         * } catch (ATUTestRecorderException e) { e.printStackTrace(); }
         */
  }
  public void onTestSuccess(ITestResult result) {
     /*
      * try { record.stop(); } catch (Exception e) { e.printStackTrace(); }
      */
     String testDescription = result.getMethod().getDescription();
     String testCaseNumber = testDescription.split("_")[0];
     String testDesc = testDescription.split("_")[1];
     String status = "PASSED";
     String exceptionType = "NA";
     String detailedError = "NA";
    
     String data ="{\
" +
           "   \\"testCaseNumber\\" : \\""+testCaseNumber+"\\",\
" +
           "   \\"status\\" : \\""+status+"\\",\
" +
           "   \\"testDescription\\" : \\""+testDesc+"\\",\
" +
           "   \\"exceptionType\\" : \\""+exceptionType+"\\",\
" +
           "   \\"detailedError\\":\\""+detailedError+"\\"\
" +
           "   \
" +
           "}";
     
  }
  @Override
  public void onTestFailure(ITestResult result) {
    
     String testDescription = result.getMethod().getDescription();
     String testCaseNumber = testDescription.split("_")[0];
     String testDesc = testCaseNumber.split("_")[1];
     String status = "FAILED";
     String exceptionType = String.valueOf(result.getThrowable().getClass().getSimpleName());
     String detailedError = String.valueOf(result.getThrowable().getMessage());
    
     String data ="{\
" +
           "   \\"testCaseNumber\\" : \\""+testCaseNumber+"\\",\
" +
           "   \\"status\\" : \\""+status+"\\",\
" +
           "   \\"testDescription\\" : \\""+testDesc+"\\",\
" +
           "   \\"exceptionType\\" : \\""+exceptionType+"\\",\
" +
           "   \\"detailedError\\":\\""+detailedError+"\\"\
" +
           "   \
" +
           "}";
    
     // TODO Auto-generated method stub
  }
  @Override
  public void onTestSkipped(ITestResult result) {
     String testDescription = result.getMethod().getDescription();
     String testCaseNumber = testDescription.split("_")[0];
     String testDesc = testCaseNumber.split("_")[1];
     String status = "SKIPPED";
     String exceptionType = result.getThrowable().getClass().getSimpleName();
     String detailedError = result.getThrowable().getMessage();
    
     String data ="{\
" +
           "   \\"testCaseNumber\\" : \\""+testCaseNumber+"\\",\
" +
           "   \\"status\\" : \\""+status+"\\",\
" +
           "   \\"testDescription\\" : \\""+testDesc+"\\",\
" +
           "   \\"exceptionType\\" : \\""+exceptionType+"\\",\
" +
           "   \\"detailedError\\":\\""+detailedError+"\\"\
" +
           "   \
" +
           "}";
  }
  @Override
  public void onTestFailedButWithinSuccessPercentage(ITestResult result) {
     // TODO Auto-generated method stub
  }
  @Override
  public void onStart(ITestContext context) {
     // TODO Auto-generated method stub
  }
  @Override
  public void onFinish(ITestContext context) {
     // TODO Auto-generated method stub
  }
}

Conclusão: Com isso, estamos concluindo o desenvolvimento do framework Selenium Page Object Model, por meio do qual você pode começar a construir o framework do modelo Page Object e levá-lo ao nível avançado. Na próxima série do tutorial, discutiremos mais sobre os recursos avançados do framework Selenium . Para passar pela série de Tutorial do Selenium que você pode ler aqui.

Deixe um comentário