错误:无法访问org.openqa.selenium.HasInputDevices,未找到类文件

问题描述 投票:0回答:2

我跑步:

mvn clean test

我收到此错误:

[错误]执行目标失败 org.apache.maven.plugins:maven-compiler-plugin:3.2:testCompile 项目 suman 上的(default-testCompile):编译失败 [错误] /home/oleg/WebstormProjects/oresoftware/sumanjs/sce-test/suman/src/test/java/suman/SeleniumTest.java:[21,15] 无法访问 org.openqa.selenium.HasInputDevices [错误] 类文件 对于 org.openqa.selenium.HasInputDevices 未找到

我正在看这个:

https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/interactions/HasInputDevices.html

看来是我的 FirefoxDriver 或 ChromeDriver 导致了该问题。

这是我的 pom.xml 文件:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>suman</groupId>
  <artifactId>suman</artifactId>
  <packaging>jar</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>suman</name>
  <url>http://maven.apache.org</url>

  <dependencies>

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.12</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>htmlunit-driver</artifactId>
      <version>2.29.0</version>
    </dependency>

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-java</artifactId>
      <version>2.21.0</version>
    </dependency>

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-chrome-driver</artifactId>
      <version>2.0rc3</version>
    </dependency>

    <dependency>
      <groupId>org.seleniumhq.selenium</groupId>
      <artifactId>selenium-firefox-driver</artifactId>
      <version>2.0rc3</version>
    </dependency>


  </dependencies>
</project>

我有两个测试脚本,一个使用 ChromeDriver,另一个使用 FirefoxDriver,它们看起来像这样:

package suman;

import java.util.concurrent.TimeUnit;
import org.junit.AfterClass;
import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Test;
import org.openqa.selenium.*;
import org.openqa.selenium.interactions.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class SeleniumTest {

    private static FirefoxDriver driver;
    private WebElement element;

    @BeforeClass
    public static void openBrowser(){
        driver = new FirefoxDriver();
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    }

    @Test
    public void valid_UserCredential(){

        System.out.println("Starting test " + new Object(){}.getClass().getEnclosingMethod().getName());
        driver.get("http://www.store.demoqa.com");
        driver.findElement(By.xpath(".//*[@id='account']/a")).click();
        driver.findElement(By.id("log")).sendKeys("testuser_3");
        driver.findElement(By.id("pwd")).sendKeys("Test@123");
        driver.findElement(By.id("login")).click();
        try{
            element = driver.findElement (By.xpath(".//*[@id='account_logout']/a"));
        }catch (Exception e){
        }
        Assert.assertNotNull(element);
        System.out.println("Ending test " + new Object(){}.getClass().getEnclosingMethod().getName());
    }


    @Test
    public void inValid_UserCredential()
    {
        System.out.println("Starting test " + new Object(){}.getClass().getEnclosingMethod().getName());
        driver.get("http://www.store.demoqa.com");
        driver.findElement(By.xpath(".//*[@id='account']/a")).click();
        driver.findElement(By.id("log")).sendKeys("testuser");
        driver.findElement(By.id("pwd")).sendKeys("Test@123");
        driver.findElement(By.id("login")).click();
        try{
            element = driver.findElement (By.xpath(".//*[@id='account_logout']/a"));
        }catch (Exception e){
        }
        Assert.assertNotNull(element);
        System.out.println("Ending test " + new Object(){}.getClass().getEnclosingMethod().getName());
    }


    @AfterClass
    public static void closeBrowser(){
        driver.quit();
    }
}

有谁知道如何修复这个编译错误?

java maven selenium pom.xml
2个回答
2
投票

您收到此错误是因为 pom.xml 中的依赖项不兼容。
依赖列表应该是这样的。

<dependencies>

    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-chrome-driver</artifactId>
        <version>3.9.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.9.1</version>
        <scope>test</scope>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-firefox-driver</artifactId>
        <version>3.9.1</version>
    </dependency>

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-server</artifactId>
        <version>3.9.1</version>
    </dependency>

</dependencies>

0
投票
package com.twomoro.aerowebb.selenium.base;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.TimeUnit;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.SkipException;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.BeforeClass;

import com.relevantcodes.extentreports.ExtentTest;
import com.relevantcodes.extentreports.LogStatus;
import com.twomoro.aerowebb.selenium.extentlisteners.Report;
import com.twomoro.aerowebb.selenium.utilities.ExcelReader;
import com.twomoro.aerowebb.selenium.utilities.SkipExecution;
import com.twomoro.aerowebb.selenium.utilities.TestUtil;

import io.github.bonigarcia.wdm.WebDriverManager;
import junit.framework.Assert;

public class BaseTest {

    public static WebDriver driver;
    public static ExtentTest logger;
    public static Properties OR = new Properties();
    public static Properties config = new Properties();
    public static FileInputStream fis;

    public static Logger log = LogManager.getLogger(BaseTest.class);

    public static ExcelReader excel = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdata.xlsx");
    public static ExcelReader keyexcel = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/data-1622036474491.xlsx");
    public static ExcelReader enggDataExcel = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdataEnggData.xlsx");
    public static ExcelReader excelFleet = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdataFleet.xlsx");
    public static ExcelReader logisticsExcel = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdataLogistics.xlsx");
    public static ExcelReader excel1 = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdata1.xlsx");
    public static ExcelReader resourcesExcel = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdataResources.xlsx");
    public static ExcelReader maintenanceExcel = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdataMaintenance.xlsx");
    public static ExcelReader testdataAPI = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdataAPI.xlsx");

    public static ExcelReader excelFlight = new ExcelReader(
            System.getProperty("user.dir") + "/src/test/resources/excel/testdataFlightOperations.xlsx");

    public static String reportFilepath = System.getProperty("user.dir") + File.separator + "reports" + File.separator
            + TestUtil.time();
    public static Report reporting = new Report(reportFilepath);
    // public static MonitoringMail mail = new MonitoringMail();
    public static WebDriverWait wait;
    public static WebElement dropdown;
    public static int reportCounter = 0;
    static WebElement ele;

    @SuppressWarnings("deprecation")
    @BeforeClass
    public void setUp() throws IOException, ClassNotFoundException {

        freemarker.log.Logger.selectLoggerLibrary(freemarker.log.Logger.LIBRARY_NONE);

        String testCaseName = this.getClass().getSimpleName();
        if (!SkipExecution.isSkipExecution(testCaseName)) {
            throw new SkipException("Runmode Is 'No' Or Blank. So Skipping Execution Of test case:  " + testCaseName);
        }

        if (driver == null) {

//          reporting.startTestCase("Pre requisite");
//          PropertyConfigurator
//                  .configure(System.getProperty("user.dir") + "\\src\\test\\resources\\properties\\log4j.properties");

            fis = new FileInputStream(
                    System.getProperty("user.dir") + "/src/test/resources/properties/Config.properties");
            try {
                config.load(fis);
                log.info("Config properties loaded");
            } catch (IOException e) {
                e.printStackTrace();
            }

            fis = new FileInputStream(System.getProperty("user.dir") + "/src/test/resources/properties/OR.properties");
            try {
                OR.load(fis);
                log.info("OR properties loaded");
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (config.getProperty("browser").equals("firefox")) {
                System.setProperty("webdriver.gecko.driver",
                        (System.getProperty("user.dir") + "/src/test/resources/executables/geckodriver.exe"));
                driver = new FirefoxDriver();
                log.info("Firefox driver launched");
//              reporting.logIntoReport(logger,LogStatus.INFO,"","Firefox driver launched succesfully");
            } else if (config.getProperty("browser").equals("chrome")) {

                WebDriverManager.chromedriver().setup();
                ChromeOptions options = new ChromeOptions().setHeadless(true);
                options.addArguments("--no-sandbox");
                System.setProperty("webdriver.chrome.args", "--disable-logging");
                System.setProperty("webdriver.chrome.silentOutput", "true");
                options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
                options.addArguments("disable-infobars"); // disabling infobars
                options.addArguments("--disable-extensions"); // disabling extensions
                options.addArguments("--disable-gpu"); // applicable to windows os only
                //options.addArguments("window-size=1325,744");// Bypass OS security model
                options.addArguments("window-size=1920, 1080");
                options.addArguments("--incognito");
//This is a One             
                driver = new ChromeDriver(options);
                log.info("Chrome driver launched");

            } else if (config.getProperty("browser").equals("ie")) {
                System.setProperty("webdriver.ie.driver",
                        (System.getProperty("user.dir") + "/src/test/resources/executables/IEDriverServer.exe"));
                driver = new InternetExplorerDriver();
                log.info("IE driver launched");

            }

            driver.get(config.getProperty("testsiteurl"));
            log.info("Navigated to URL " + config.getProperty("testsiteurl"));
//          reporting.logIntoReport(logger,LogStatus.INFO,"","Navigated to URL " + config.getProperty("testsiteurl"));
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(Integer.parseInt(config.getProperty("implict.wait")),
                    TimeUnit.SECONDS);
            wait = new WebDriverWait(driver, Integer.parseInt(config.getProperty("explicit.wait")));

        } else {
//          PropertyConfigurator
//                  .configure(System.getProperty("user.dir") + "\\src\\test\\resources\\properties\\log4j.properties");
            fis = new FileInputStream(
                    System.getProperty("user.dir") + "/src/test/resources/properties/Config.properties");
            try {
                config.load(fis);
                log.info("Config properties loaded");
            } catch (IOException e) {
                e.printStackTrace();
            }

            fis = new FileInputStream(System.getProperty("user.dir") + "/src/test/resources/properties/OR.properties");
            try {
                OR.load(fis);
                log.info("OR properties loaded");
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (config.getProperty("browser").equals("firefox")) {
                System.setProperty("webdriver.gecko.driver",
                        (System.getProperty("user.dir") + "/src/test/resources/executables/geckodriver.exe"));
                driver = new FirefoxDriver();
                log.info("Firefox driver launched");
//              reporting.logIntoReport(logger,LogStatus.INFO,"","Firefox driver launched succesfully");
            } else if (config.getProperty("browser").equals("chrome")) {

                WebDriverManager.chromedriver().setup();
                ChromeOptions options = new ChromeOptions().setHeadless(true);
                options.addArguments("--no-sandbox");
                System.setProperty("webdriver.chrome.args", "--disable-logging");
                System.setProperty("webdriver.chrome.silentOutput", "true");
                options.addArguments("--disable-dev-shm-usage"); // overcome limited resource problems
                options.addArguments("disable-infobars"); // disabling infobars
                options.addArguments("--disable-extensions"); // disabling extensions
                options.addArguments("--disable-gpu"); // applicable to windows os only
            //  options.addArguments("window-size=1325,744"); // Bypass OS security model
                options.addArguments("window-size=1920, 1080");
                options.addArguments("--incognito");
                driver = new ChromeDriver(options);
                log.info("Chrome driver launched");

            } else if (config.getProperty("browser").equals("ie")) {
                System.setProperty("webdriver.ie.driver",
                        (System.getProperty("user.dir") + "/src/test/resources/executables/IEDriverServer.exe"));
                driver = new InternetExplorerDriver();
                log.info("IE driver launched");
//              reporting.logIntoReport(logger,LogStatus.INFO,"","IE driver launched succesfully");
            }

            driver.get(config.getProperty("testsiteurl"));
            log.info("Navigated to URL " + config.getProperty("testsiteurl"));
            driver.manage().deleteAllCookies();
            driver.manage().window().maximize();
            driver.manage().timeouts().implicitlyWait(Integer.parseInt(config.getProperty("implict.wait")),
                    TimeUnit.SECONDS);
            wait = new WebDriverWait(driver, Integer.parseInt(config.getProperty("explicit.wait")));
        }

    }

    public static void click(String locatorKey) throws IOException {
        try {

            driver.findElement(By.xpath(locatorKey)).click();

            // log.info("Clicking on an Element : " + locatorKey);
        } catch (Throwable t) {
            log.info("Error while clicking on element :" + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while clicking on element :"
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while clicking on element :" + locatorKey);
            return;
        }
    }

    public static WebElement getObject(String locatorKey) throws IOException {
        WebElement element = null;

        try {
            element = driver.findElement(By.id(locatorKey));

            return element;
        } catch (Throwable t) {

            log.info("Error while finding an element : " + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while finding an element : "
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while finding an element : " + locatorKey + " exception message is : "
                    + t.getLocalizedMessage());
            return element;
        }
    }

    public static void click(WebElement locatorKey) throws IOException {
        try {
            locatorKey.click();

            // log.info("Clicking on an Element : " + locatorKey);
        } catch (Throwable t) {
            log.info("Error while clicking on element :" + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while clicking on element :"
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while clicking on element :" + locatorKey);
            return;
        }
    }

    public static void clickjs(String locatorKey) throws IOException {

        try {

            JavascriptExecutor executor = (JavascriptExecutor) driver;
            executor.executeScript("arguments[0].click();", driver.findElement(By.xpath(locatorKey)));

        } catch (StaleElementReferenceException e) {

            WaitStatementsLib.waitForElementToPresent(driver, 60, By.xpath(locatorKey));
            JavascriptExecutor executor = (JavascriptExecutor) driver;
            executor.executeScript("arguments[0].click();", driver.findElement(By.xpath(locatorKey)));

        } catch (Throwable t) {
            log.info("Error while clicking on element :" + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while clicking on element :"
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while clicking on element : " + locatorKey);
            return;
        }
    }

    public static void clickjs_before(String locatorKey) throws IOException {
        WebElement cljs;
        JavascriptExecutor executor1 = (JavascriptExecutor) driver;
        cljs = driver.findElement(By.xpath(locatorKey));
        executor1.executeScript("arguments[0].click();", cljs);
        log.info("Clicking on an Element : " + locatorKey);
    }

    public static void clickjs(WebElement locatorKey) throws IOException {
        JavascriptExecutor executor1 = (JavascriptExecutor) driver;
        try {
            executor1.executeScript("arguments[0].click();", locatorKey);

            // log.info("Clicking on an Element : " + locatorKey);
        } catch (Throwable t) {
            log.info("Error while clicking on element :" + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while clicking on element :"
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while clicking on element : " + locatorKey);
            return;
        }
    }

    public static void type(String locatorKey, String value) throws IOException {
        try {
            driver.findElement(By.xpath(locatorKey)).clear();
            WaitStatementsLib.iWait(5);
            driver.findElement(By.xpath(locatorKey)).sendKeys(value);

            // log.info("Typing in an Element : " + locatorKey + " entered the value as : "
            // + value);
        } catch (Throwable t) {
            log.info("Error while type on element : " + locatorKey + " ,exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while type on element : "
                    + locatorKey + " ,exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while type on element : " + locatorKey);
            return;
        }

    }

    public static void type(WebElement locatorKey, String value) throws IOException {
        try {

            locatorKey.clear();
            WaitStatementsLib.iWait(3);
            locatorKey.sendKeys(value);

            // log.info("Typing in an Element : " + locatorKey + " entered the value as : "
            // + value);
        } catch (Throwable t) {
            log.info("Error while type on element : " + locatorKey + " ,exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while type on element : "
                    + locatorKey + " ,exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while type on element : " + locatorKey);
            return;
        }

    }

    public static void select(String locatorKey, String value) throws IOException {
        try {

            dropdown = driver.findElement(By.xpath(locatorKey));
            Select select = new Select(dropdown);
            select.selectByVisibleText(value);

            // log.info("Typing in an Element : " + locatorKey + " entered the value as : "
            // + value);
        } catch (Throwable t) {
            log.info("Error while select on element : " + locatorKey + " ,exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while select on element : "
                    + locatorKey + " ,exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while select on element : " + locatorKey);
            return;
        }
    }

    public static void select(WebElement locatorKey, String value) throws IOException {
        try {

            dropdown = locatorKey;
            Select select = new Select(dropdown);
            select.selectByVisibleText(value);

            // log.info("Typing in an Element : " + locatorKey + " entered the value as : "
            // + value);
        } catch (Throwable t) {
            log.info("Error while select on element : " + locatorKey + " ,exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while select on element : "
                    + locatorKey + " ,exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while select on element : " + locatorKey);
            return;
        }
    }

    public static boolean isElementPresent(String locatorKey) throws IOException {
        try {
            driver.findElement(By.xpath(locatorKey));
            // log.info("Finding the Element : " + locatorKey);
            return true;
        } catch (Throwable t) {

            log.info("Error while finding an element : " + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while finding an element : "
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while isElementPresent on element : " + locatorKey);
            return false;

        }

    }

    public static boolean isElementPresent(WebElement locatorKey) throws IOException {
        try {
            if (locatorKey.toString().contains("Proxy")) {
                // log.info("Error while finding an element : " + locatorKey);
                Assert.fail("Error while isElementPresent on element : " + locatorKey);
                return false;
            } else {
                log.info("Finding the Element : " + locatorKey.toString());
            }
            return true;

        } catch (Throwable t) {
            log.info("Error while finding an element : " + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while finding an element : "
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while isElementPresent on element : " + locatorKey);
            return false;

        }

    }

    public static boolean isElementSelected(String locatorKey) throws IOException {
        try {
            Boolean isSelected = false;

            isSelected = driver.findElement(By.xpath(locatorKey)).isSelected();

            // log.info("Finding the Element : " + locatorKey);
            return isSelected;
        } catch (Throwable t) {

            log.info("Error while finding an element : " + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while finding an element : "
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while isElementPresent on element : " + locatorKey);
            return false;

        }
    }

    public static boolean isElementSelected(WebElement locatorKey) throws IOException {
        try {
            Boolean isSelected = false;

            isSelected = locatorKey.isSelected();

            // log.info("Finding the Element : " + locatorKey);
            return isSelected;
        } catch (Throwable t) {

            log.info("Error while finding an element : " + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while finding an element : "
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while isElementPresent on element : " + locatorKey);
            return false;

        }
    }

    /*
     * public static boolean mandatory(String locatorKey) throws IOException { try {
     * if (locatorKey.endsWith("_XPATH")) { ele
     * =driver.findElement(By.xpath(OR.getProperty(locatorKey))); } else if
     * (locatorKey.endsWith("_CSS")) { ele =
     * driver.findElement(By.cssSelector(OR.getProperty(locatorKey))); } else if
     * (locatorKey.endsWith(OR.getProperty("_ID"))) { ele =
     * driver.findElement(By.id(locatorKey)); }
     * 
     * log.info("Finding the Element : " + locatorKey); JavascriptExecutor js =
     * (JavascriptExecutor)driver; return
     * (js.executeScript("return window.getComputedStyle(arguments[0], ':after')." +
     * "getPropertyValue('content');", ele).toString().contains("*")); } catch
     * (Throwable t) {
     * 
     * log.info("Error while finding an element : " + locatorKey +
     * " exception message is : " + t.getMessage());
     * reporting.logIntoReport(logger,LogStatus.FAIL,
     * "","<font color='Red'>Error while finding an element : " + locatorKey +
     * " exception message is : " + t.getLocalizedMessage());
     * Assert.fail("Error while finding an element : " + locatorKey +
     * " exception message is : " + t.getLocalizedMessage()); return false; }
     * 
     * 
     * }
     */
    public static boolean mandatory(String locatorKey) throws IOException {
        try {

            ele = driver.findElement(By.xpath(locatorKey));

            // log.info("Finding the Element : " + locatorKey);
            JavascriptExecutor js = (JavascriptExecutor) driver;
            return (js.executeScript(
                    "return window.getComputedStyle(arguments[0], ':after')." + "getPropertyValue('content');", ele)
                    .toString().contains("*"));
        } catch (Throwable t) {

            log.info("Error while finding an element : " + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while finding an element : "
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while finding an element : " + locatorKey + " exception message is : "
                    + t.getLocalizedMessage());
            return false;
        }

    }

    public static boolean mandatory(WebElement ele) {

        JavascriptExecutor js = (JavascriptExecutor) driver;
        return (js
                .executeScript(
                        "return window.getComputedStyle(arguments[0], ':after')." + "getPropertyValue('content');", ele)
                .toString().contains("*"));

    }

    /**
     * Function to get the WebElement for input string locator
     * 
     * @param locatorKey
     * @return WebElement
     * @throws IOException
     */
    /*
     * public static WebElement getWeblement(String locatorKey) throws IOException {
     * WebElement element = null;
     * 
     * try { if (locatorKey.endsWith("_XPATH")) { element =
     * driver.findElement(By.xpath(OR.getProperty(locatorKey))); } else if
     * (locatorKey.endsWith("_CSS")) { element =
     * driver.findElement(By.cssSelector(OR.getProperty(locatorKey))); } else if
     * (locatorKey.endsWith(OR.getProperty("_ID"))) { element =
     * driver.findElement(By.id(locatorKey)); }
     * 
     * 
     * return element; } catch (Throwable t) {
     * 
     * log.info("Error while finding an element : " + locatorKey +
     * " exception message is : " + t.getMessage()); reporting.logIntoReport(logger,
     * LogStatus.FAIL, "", "<font color='Red'>Error while finding an element : " +
     * locatorKey + " exception message is : " + t.getLocalizedMessage());
     * Assert.fail("Error while finding an element : " + locatorKey +
     * " exception message is : " + t.getLocalizedMessage()); return element; } }
     */
    public static WebElement getWeblement(String locatorKey) throws IOException {
        WebElement element = null;

        try {
            element = driver.findElement(By.xpath(locatorKey));
            return element;
        } catch (Throwable t) {

            log.info("Error while finding an element : " + locatorKey + " exception message is : " + t.getMessage());
            reporting.logIntoReport(logger, LogStatus.FAIL, "", "<font color='Red'>Error while finding an element : "
                    + locatorKey + " exception message is : " + t.getLocalizedMessage());
            Assert.fail("Error while finding an element : " + locatorKey + " exception message is : "
                    + t.getLocalizedMessage());
            return element;
        }
    }

    /**
     * Method to make xpath based on variable passed ex. xpath string :
     * "//span[text()=<token>]";
     * 
     * @param element: String value of xpath
     * @param token:   String value of variable
     * @return WebElement: WebElement xpath
     */
    public WebElement getVariablexPath(String element, String token) {
        String start = "", end = "";
        if (element.contains("<") || element.contains(">")) {
            start = element.substring(0, element.indexOf("<"));
            end = element.substring(element.indexOf(">") + 1, element.length());
        }
        // System.out.println("getVariablexPath - " + start + "'" + token + "'" + end);
        return driver.findElement(By.xpath(start + "'" + token + "'" + end));
    }

    public static boolean clickJS(WebElement element) {
        boolean clicked = false;
        try {
            ((JavascriptExecutor) driver).executeScript("arguments[0].click();", element);
            clicked = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return clicked;
    }

    public boolean selectDropdownValue(String DropDownXpath, String value) {
        boolean clicked = false;
        try {
            WebElement dropdown = driver.findElement(By.xpath("DropDownXpath"));
            dropdown.click();
            List<WebElement> techData = driver.findElements(By.xpath("//li[@role='option']"));
            for (WebElement element : techData) {
                if (element.getAttribute("aria-label").contentEquals(value)) {
                    element.click();
                    break;
                }
            }
            clicked = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return clicked;
    }

    public boolean selectDropdownValue(WebElement DropDownid, String value) {
        boolean clicked = false;
        try {
            DropDownid.click();
            List<WebElement> techData = driver.findElements(By.xpath("//li[@role='option']"));
            for (WebElement element : techData) {
                if (element.getAttribute("aria-label").contentEquals(value)) {
                    element.click();
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();

        }
        return clicked;
    }

    @AfterClass
    public void tearDown() throws IOException {
        driver.quit();
    }

    @AfterSuite
    public void tearDown1() throws IOException {
        driver.quit()`enter code here`;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.