chromedriver NullPointerException error on linux - java

I'm currently learning selenium. I have followed a step by step walkthrough on how to start selenium-chromedriver. However I am experiencing this error here and I am have no idea how to solve it.
The following are the source code the walkthrough has given me.
package driverUtilities;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class DriverUtilities {
private static DriverUtilities instanceOfDriverUtilities;
private WebDriver driver;
public static DriverUtilities getInstanceOfDriverUtilities() {
if (instanceOfDriverUtilities == null) {
instanceOfDriverUtilities = new DriverUtilities();
}
return instanceOfDriverUtilities;
}
public WebDriver getDriver() {
if (driver == null) {
CreateDriver();
}
return driver;
}
private String GetDriverName() {
Properties config = new Properties();
String driverName = "";
try {
config.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
System.out.println("Config file is not present");
e.printStackTrace();
} catch (IOException e) {
System.out.println("Error when loading config file");
e.printStackTrace();
}
for (String key : config.stringPropertyNames()) {
if (key.equals("browser")) {
driverName = config.getProperty(key);
}
}
return driverName;
}
private void CreateDriver() {
String driverName = GetDriverName();
switch (driverName) {
case "Google Chrome":
System.setProperty("webdriver.chrome.driver", "chromedriver");
this.driver = new ChromeDriver();
break;
case "Firefox":
System.setProperty("webdriver.gecko.driver", "geckodriver.exe");
this.driver = new FirefoxDriver();
break;
default:
break;
}
}
}
This is the Driver Utilities class
package test;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import driverUtilities.DriverUtilities;
public class Mod08_Slide_16_Navigation_Commands {
#Test
public void navigationCommands() {
DriverUtilities myDriverUtilities = new DriverUtilities();
WebDriver driver = myDriverUtilities.getDriver();
System.out.println("Start the Test Case");
// Load the website - http://www.bbc.co.uk
driver.get("http://www.bbc.co.uk");
System.out.println("\nLoad the website - http://www.bbc.co.uk");
// Refresh the page
driver.navigate().refresh();
System.out.println("\nRefresh the page");
// Load the website - http://www.google.co.uk
driver.get("http://www.google.co.uk");
System.out.println("\nLoad the website - http://www.google.co.uk");
// Go back to the website - http://www.bbc.co.uk
driver.navigate().back();
System.out.println("\nGo back to the website - http://www.bbc.co.uk");
// Go forward to the website - http://www.google.co.uk
driver.navigate().forward();
System.out.println("\nGo forward to the website - http://www.google.co.uk");
// Close the browser window
driver.close();
System.out.println("\nClose the browser window");
System.out.println("\nEnd of Test Case \"Navigation Commands\"");
}
}
This is the java test class I am trying to make work of
# Change the browser to use for testing purposes, accepted values are Google Chrome and Firefox
browser=Google Chrome
I also have the pom.xml file and a config.properties file and will share it if its required.
Note: My assumptions is that the setproperty function is not locating the correct path to chromedriver. However, I'm a arch linux user thus I'm not sure if the value inside the setproperty function is set to "chromedriver" or "/usr/bin/chromedriver"
Note 1: I have navigated to the .metadata of the Eclipse IDE and deleted it after reading some stackoverflow posts. However, this did not work*
Note 2: I am completely new to Selenium however, I have some experiences with Java and understand that nullpointerexception occurs when I declare a variable but did not create an object and assign that variable to it.
Edit 1: I have included the config.properties as specified

One suggestion I have is to hard-code the creation of the driver (without config.properties) and once you have the code working, you can work on optimizations such as dynamically creating the web driver based on a key value like you are doing here. To do this, simply replace this line
WebDriver driver = myDriverUtilities.getDriver();
with
System.setProperty("webdriver.chrome.driver", "C:\\Program Files\\WebDrivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
Obviously, make sure the path to the chromedriver.exe is resolved correctly for your system. By the way, unless your web drivers are in the root folder of your code project, that path is not correct. I will double check that is the case.
I ran your code with this recommendation and it worked. That tells me either your web driver path is not correct, or there is something funky with your config.properties.
Lastly, this loop isn't correct either
for (String key : config.stringPropertyNames()) {
if (key.equals("browser")) {
driverName = config.getProperty(key);
}
}
You don't want to loop through all your browser keys. If you have more than one "key", it will iterate through them and return the last one found. Instead, you need to call getProperty() once your properties file is loaded:
String propValue = props.getProperty("browser");
Then, once you have the correct propValue, you should pass it to your switch to properly instantiate the web driver.
switch(propValue) {
case "chrome":
this.driver = new ChromeDriver();
break;
case "firefox":
this.driver = new GeckoDriver();
break;
default:
// throw some exception here
throw new IllegalArgumentException(propValue + " is not a supported browser.");
}

Related

RemoteWebDriver is null error (sauce labs implementation) -selenium,cucumber,java

I am implementing my code to work on remote machines on Sauce Labs. The code worked fine until I have changed my driver initialisation (to work with remote server). I keep getting this.driver is null exception. I don't know what's wrong with it, I was following official documentation and tried many things. I hope someone can see the issue here. Thank you in advance. My code:
DRIVER:(my username and key are copied from my sauce labs account, renamed for this purpose)
public class Hooks {
public RemoteWebDriver driver;
public WebDriverWait wait;
#Before
public void setup(Scenario scenario) throws MalformedURLException {
String username = System.getenv("my username");
String accessKey = System.getenv("key");
ChromeOptions chromeOpts = new ChromeOptions();
MutableCapabilities sauceOpts = new MutableCapabilities();
sauceOpts.setCapability("name", scenario.getName());
sauceOpts.setCapability("username", username);
sauceOpts.setCapability("accessKey",accessKey);
MutableCapabilities browserOptions = new MutableCapabilities();
browserOptions.setCapability(ChromeOptions.CAPABILITY, chromeOpts);
browserOptions.setCapability("sauce:options", sauceOpts);
browserOptions.setCapability("browserName", "chrome");
browserOptions.setCapability("browserVersion", "latest");
browserOptions.setCapability("platformName", "Windows 10");
String sauceUrl = "https://ondemand.us-west-1.saucelabs.com:443/wd/hub";
URL url = new URL(sauceUrl);
driver = new RemoteWebDriver(url, browserOptions);
wait = new WebDriverWait(driver, Duration.ofSeconds(10));
}
#After
public void tearDown(Scenario scenario) {driver.quit();}
}
PAGE OBJECT WHERE MY CODE IS: (shortened for privacy purposes)
public class LandingPO extends Hooks {
static RemoteWebDriver driver;
static WebDriverWait wait;
String url = "https://google.com"
public void openUrl() {
driver.get(url);}
And then I just call this method (landingPO.openUrl();) in my stepDefinition class.
The error is thrown where first driver usage is found:
Step failed
java.lang.NullPointerException: Cannot invoke "org.openqa.selenium.remote.RemoteWebDriver.get(String)" because "pageObjects.LandingPO.driver" is null
it breaks right at "driver.get(url)" in my LandingPO
If anyone will have the same problem, the answer was:
I was using wrong Before/After import. The correct import should be:
import io.cucumber.java.After;
import io.cucumber.java.Before;

Generate PDF with selenium chrome driver

To generate PDF from a HTML file, I want to use selenium Chrome driver.
I tried it with command line :
chrome.exe --headless --disable-gpu --print-to-pdf file:///C:invoiceTemplate2.html
and it works perfectly, So I wanted to do that with JAVA and here's my code :
System.setProperty("webdriver.chrome.driver", "C:/work/chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--print-to-pdf",
"file:///C:/invoiceTemplate2.html");
WebDriver driver = new ChromeDriver(options);
driver.quit();
The server is started with no problem, but chrome is opened with multiple tabs with the arguments I specified in Options.
Any solution to this ? thx.
This can indeed be done with Selenium and ChromeDriver (tested with Chrome version 85), but using the "print-to-pdf" option when starting Chrome from the webdriver is not the solution.
The thing to do is to use the command execution functionality of ChromeDriver:
https://www.selenium.dev/selenium/docs/api/java/org/openqa/selenium/remote/RemoteWebDriver.html#execute-java.lang.String-java.util.Map-
There is a command called Page.printToPDF that provides PDF output functionality. A dictionary containing the item "data", with the resulting PDF in base-64-encoded format, is returned.
Unfortunately, I do not have a full Java example, but in this answer, there is a C# example (Selenium methods are named differently in C# compared to Java, but the principle should be the same):
https://stackoverflow.com/a/63970792/2416627
The Page.printToPDF command in Chrome is documented here:
https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF
UPDATE:
we noticed that the original workaround was not always working properly, and we went for a Selenium + ChromeDriver:
public void generatePdf(Path inputPath, Path outputPath) throws Exception
{
try
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--headless", "--disable-gpu", "--run-all-compositor-stages-before-draw");
ChromeDriver chromeDriver = new ChromeDriver(options);
chromeDriver.get(inputPath.toString());
Map<String, Object> params = new HashMap();
String command = "Page.printToPDF";
Map<String, Object> output = chromeDriver.executeCdpCommand(command, params);
try
{
FileOutputStream fileOutputStream = new FileOutputStream(outputPath.toString());
byte[] byteArray = java.util.Base64.getDecoder().decode((String) output.get("data"));
fileOutputStream.write(byteArray);
fileOutputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
catch (Exception e)
{
e.printStackTrace(System.err);
throw e;
}
}
If this will be called frequently I suggest reusing the driver object because it takes a while to initialize.
Remember to close or quit the driver to avoid leaving Zombie chrome processes behind and also remember to install ChromeDriver in your machine.
Original Solution:
Not being able to get the desired outcome using ChromeDriver my workaround was to call the headless chrome in the command-line from my Java program.
This is working on Windows but just changing the contents of the paths used in the command variable should make it work in Linux too.
public void generatePdf(Path inputPath, Path outputPath) throws Exception {
try {
String chromePath = "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe";
String command = chromePath + " --headless --disable-gpu --run-all-compositor-stages-before-draw --print-to-pdf=" + outputPath.toString() + " " + inputPath.toString();
// Runs "chrome" Windows command
Process process = Runtime.getRuntime().exec(command);
process.waitFor(); // Waits for the command's execution to finish
}catch (Exception e){
e.printStackTrace(System.err);
throw e;
}finally{
// Deletes files on exit
input.toFile().deleteOnExit();
output.toFile().deleteOnExit();
}
}
Note: both input and output paths are temporary files created with NIO.
The code will help you save the page in PDF format on Selenium c#
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
protected void PDFconversion(ChromeDriver driver, string root, string rootTemp)
{
//Grid.Rows.Add(TxtBxName.Text, TxtBxAddress.Text);
try
{
IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
Thread.Sleep(500);
js.ExecuteScript("setTimeout(function() { window.print(); }, 0);");
Thread.Sleep(500);
driver.SwitchTo().Window(driver.WindowHandles.Last());
Thread.Sleep(500);
string JSPath = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('#destinationSettings').shadowRoot.querySelector('#destinationSelect').shadowRoot.querySelector('print-preview-settings-section:nth-child(9)>div>select>option:nth-child(3)')";
Thread.Sleep(500);
IWebElement PrintBtn = (IWebElement)js.ExecuteScript($"return {JSPath}");
Thread.Sleep(500);
PrintBtn.Click();
string JSPath1 = "document.querySelector('body>print-preview-app').shadowRoot.querySelector('#sidebar').shadowRoot.querySelector('print-preview-button-strip').shadowRoot.querySelector('cr-button.action-button')";
Thread.Sleep(1000);
IWebElement PrintBtn1 = (IWebElement)js.ExecuteScript($"return {JSPath1}");
PrintBtn1.Click();
Thread.Sleep(1000);
SendKeys.Send("{HOME}");
SendKeys.Send(rootTemp + "\\" + "result.pdf"); // Path
SendKeys.Send("{TAB}");
SendKeys.Send("{TAB}");
SendKeys.Send("{TAB}");
SendKeys.Send("{ENTER}");
Thread.Sleep(1000);
}
catch (Exception ex){}
}
You have to do two things.
First: Make a screenshot using selenium.
Second: Convert that screenshot using any pdf tool, like itext. Here I am showing a complete example of how to do this.
Step 1: Download the jar of itext from here and add the jar file to your build path.
Step 2: Add this code to your project.
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--print-to-pdf");
WebDriver driver = new ChromeDriver(options);
driver.get("file:///C:/invoiceTemplate2.html");
try {
File screenshot = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshot, new File("screenshot.png"));
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("webaspdf.pdf"));
document.open();
Image image = Image.getInstance("screenshot.png");
document.add(image);
document.close();
}
catch (Exception e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
Note: To use the mentioned itext package, add the required imports to your code.
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;

The driver executable does not exist: D:\Firefox\geckodriver.exe

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class sasas {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.gecko.driver","D:\\Firefox\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.manage().window().maximize();
driver.get(appUrl);
System.out.println("Test script executed successfully.");
driver.close();
}
}
this is the sample code i am trying. when i run i get the error message as "The driver executable does not exist: D:\Firefox\geckodriver.exe" please help me to proceed. i added the location in environmental variable then too i get this error . PATH i added as D:\Samplecode.
kindly help me
(1) To use gecko driver, make sure you are using Firefox version 55 and above to get better gecko Web-Driver feature support, find out more here
(2) Perhaps, you should downgrade Selenium to a lower version i.e. version 2.53.1. Selenium version 2.53.1 runs perfectly on Firefox 47.0.1 and lower, does not require using web driver API. I have ran your code against this and it worked fine.
public class Sasas {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
String appUrl = "https://accounts.google.com";
driver.manage().window().maximize();
driver.get(appUrl);
System.out.println("Test script executed successfully.");
driver.close();
}
}
Use the relative path:
JAVA
1.- In your project, create the Drivers/Win/Firefox/geckodriver.exe folder and add your .exe
2.- Replace:
System.setProperty("webdriver.gecko.driver","D:\\Firefox\\geckodriver.exe");
For:
String path = System.getProperty("user.dir") + "/Drivers/Win/Firefox/Geckodriver.exe";
System.setProperty("webdriver.gecko.driver", path);
Note: using the relative path is the most optimal

Selenium WebDriver using TestNG and Excel

Hello i really need help with Selenium WebDriver using TestNG and Excel
i try to get data from excel to open browser and navigate URL. its work successfully and terminal and testng report showing test pass but its not open browser or doing anything its just run its self and show report
Config File
public void openBrowser(String browser){
try {
if (browser.equals("Mozilla")) {
driver = new FirefoxDriver();
} else if(browser.equals("IE")){
driver = new InternetExplorerDriver();
} else if(browser.equals("Chrome")){
System.setProperty("webdriver.chrome.driver", "\\Applications\\Google Chrome.app\\Contents\\MacOS\\Google Chrome ");
driver = new ChromeDriver();
}
} catch (Exception e) {
}
}
public void navigate(String baseUrl){
try {
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.navigate().to(baseUrl);
} catch (Exception e) {
}
}
And Test Execute File
public class NewTest {
public String exPath = Config.filePath;
public String exName = Config.fileName;
public String exWrSheet = "Logiin Functional Test";
public Config config;
#BeforeTest
public void openBrowser() {
config = new Config();
Excel.setExcelFile(exPath+exName, exWrSheet);
String browser = Excel.getCellData(1, 2);
config.openBrowser(browser);
}
#BeforeMethod
public void navigate() {
config = new Config();
Excel.setExcelFile(exPath+exName, exWrSheet);
String baseUrl = Excel.getCellData(2, 2);
config.navigate(baseUrl);
}
#Test
public void test() {
System.out.println("Test");
}
#AfterTest
public void closeBroser() {
//Config.tearDown();
}
I don't have quite enough rep to make a comment, which I would prefer here, but if you aren't getting any sort of exception, I'd suspect the value you're getting for the browser variable is not matching anything in your if-then-else in openBrowser and then falling through. Step through the code with a debugger or just add:
String browser = Excel.getCellData(1, 2);
System.out.println("Browser value from Excel =" + browser);
config.openBrowser(browser);
to see what you're reading from the file.
1 - TestNg is always pass because you are using "void" method and you catch "all" exception
2 - No browser opened because in openBrowser(String browser), NullPointException throws and you already catch it.
-> you need to init an instance of WebDriver and pass it through your test.

Attempting to execute Selenium IDE exported code and getting this runtime error: Exception in thread "main" java.lang.NoSuchMethodError: main

My end goal is to confirm that I have Java, Selenium WebDriver, and JUnit functioning such that I can run an automated test case utilizing these technologies.
What I have done so far:
installed Selenium IDE (v 2.8.0) for Firefox (v 34.0.5)
recorded a simple test case using Selenium IDE and added the test case to a test suite
in Selenium IDE exported the test case using the option: File->Export Test Case As...->Java / JUnit 4 / WebDriver
downloaded and installed JUnit 4 from: https://github.com/junit-team/junit/wiki/Download-and-Install (Plain-old jar method)
downloaded and installed Selenium client and WebDriver Java language binding (v 2.44.0) from: http://www.seleniumhq.org/download/
performed some slight modifications to the code generated in step 3 such as removing the package statement at the beginning
compiled the code with the following command (windows command prompt):
C:\docs\tech\code\myCode\java\testing\selenium\utest\practice>C:\java\jdk\bin\javac.exe -cp C:\docs\installs\programming\automation\test\xUnit\java\jUnit\junit\v4_12\junit-4.12.jar;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\hamcrest\hamcrest-core-1.3.jar;C:\docs\installs\programming\automation\web\selenuim\webdriver\java\selenium-2.44.0\selenium-java-2.44.0.jar C:\docs\tech\code\myCode\java\testing\selenium\utest\practice\TestGooglePlayApp.java
this compiles with no warnings/errors
attempt to execute the code with the following command:
C:\docs\tech\code\myCode\java\testing\selenium\utest\practice>java -cp .;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\junit\v4_12\junit-4.12.jar;C:\docs\installs\programming\automation\test\xUnit\java\jUnit\hamcrest\hamcrest-core-1.3.jar;C:\docs\installs\programming\automation\web\selenuim\webdriver\java\selenium-2.44.0\selenium-java-2.44.0.jar TestGooglePlayApp
Actual Result:
The output of this attempt is:
Exception in thread "main" java.lang.NoSuchMethodError: main
No other error/warning is given and no indication is given that the code begins to execute
Expected Result:
This is my first time interacting with these technologies so I'm learning as I go! However, based on the research I have done my expectation is that a local Selenium WebDriver instance will be initialized as a Firefox Driver. This Firefox Driver will be sent instructions by the Java code in order to carry out the steps in the test case. JUnit will then indicate somehow on the command line the Pass/Fail status of the test case.
The big assumption I have here is that the Selenium Server/Selenium RC is not required in this case since all I intend to do is execute a local Selenium WebDriver script. Furthermore, my hope is that this can be launched directly from the command-line independent of Eclipse, Maven, etc. I would like to be able to send the final Java class to a colleague and the only dependency for expected execution would be a working SDK of Java on the end machine.
What's Next?
I'm looking for advice on what I can do to get this code up and running under the restraints I have outlined. It may be that the code needs to be modified. It may be that my expectations need to be tempered down and it's just not possible to do everything I want directly from the command-line. It may be that I did not compile the code correctly or some library is missing. It may be that... okay you get the point!
Other Relevant Details:
OS = Windows 7 - 64 bit
Here is the contents of TestGoogleApp.java:
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class TestGooglePlayApp {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.google.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void test000() throws Exception {
driver.get("http://www.google.com/");
// COMMENT: Assert the 'Apps' icon is present and then click on it
assertTrue(isElementPresent(By.cssSelector("a.gb_C.gb_Sa")));
driver.findElement(By.cssSelector("a.gb_C.gb_Sa")).click();
// COMMENT: Assert the 'Play' app is present and then click on the 'Play' app and wait for the expected contents to load
assertTrue(isElementPresent(By.cssSelector("#gb78 > span.gb_s")));
driver.findElement(By.cssSelector("#gb78 > span.gb_s")).click();
// COMMENT: Assert that the input element associated with search queries is present and then type 'Testing' in the input element associated with search queries
assertTrue(isElementPresent(By.id("gbqfq")));
driver.findElement(By.id("gbqfq")).clear();
driver.findElement(By.id("gbqfq")).sendKeys("Testing");
// COMMENT: Click on the 'Search' element to perform a query for the input query term previously entered and wait for the expected contents to load
driver.findElement(By.id("gbqfb")).click();
// COMMENT: Assert that the desired result is contained in the search results returned and then click on the desired search result and wait for the expected contents to load
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.linkText("Software Testing Concepts"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
driver.findElement(By.linkText("Software Testing Concepts")).click();
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if ("Software Testing Concepts - Android Apps on Google Play".equals(driver.getTitle())) break; } catch (Exception e) {}
Thread.sleep(1000);
}
// COMMENT: Assert that the page contains the expected content as follows: 1) title of app 2) user rating 3) number of users who have rated the app 4) format of text value of user rating (4.0) 5) format of text value for number of user who have rated the app (128)
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.cssSelector("div.score"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
for (int second = 0;; second++) {
if (second >= 60) fail("timeout");
try { if (isElementPresent(By.cssSelector("span.reviews-num"))) break; } catch (Exception e) {}
Thread.sleep(1000);
}
try {
assertTrue(Pattern.compile("[0-9]\\.[0-9]").matcher(driver.findElement(By.cssSelector("div.score")).getText()).find());
} catch (Error e) {
verificationErrors.append(e.toString());
}
try {
assertTrue(Pattern.compile("[0-9]+").matcher(driver.findElement(By.cssSelector("span.reviews-num")).getText()).find());
} catch (Error e) {
verificationErrors.append(e.toString());
}
// COMMENT: store value for user rating and store value for number of users who have rated the app
String _currentUserRating = driver.findElement(By.cssSelector("div.score")).getText();
System.out.println(_currentUserRating);
String _numOfUserRatings = driver.findElement(By.cssSelector("span.reviews-num")).getText();
System.out.println(_numOfUserRatings + "HELLO");
}
#After
public void tearDown() throws Exception {
driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}

Categories