Handling Errors Thrown By Selenium - java

Let's say I have an object:
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class SOClass {
private WebDriver driver;
private List<String> dataString;
public SOClass(WebDriver driver) throws ArrayIndexOutOfBoundsException {
this.driver = driver;
prepData();
}
private void prepData() throws ArrayIndexOutOfBoundsException {
List<WebElement> data = this.driver.findElements(By.className("a-export-table"));
if(data.isEmpty()) {
throw new ArrayIndexOutOfBoundsException("There was no data in the table to export");
}
for(WebElement w : data) {
this.dataString.add(w.getText());
}
}
public void export(String path) throws IOException {
FileWriter fw = new FileWriter(path);
boolean isFirst = false;
for(String s : this.dataString) {
if(isFirst) {
fw.append(s);
} else {
fw.append("," + s);
}
}
fw.flush();
fw.close();
}
}
and main:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class SOMain {
private static final String COMPUTER_NAME = System.getProperty("user.name");
private static final String CHROME_PATH =
"C:/Users/" + COMPUTER_NAME + "/selenium/chromedriver.exe";
private static final String OUT_PATH = "C:/Users/" + COMPUTER_NAME + "/output/export.csv";
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", CHROME_PATH);
ChromeOptions options = new ChromeOptions();
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(ChromeOptions.CAPABILITY, options);
WebDriver driver = new RemoteWebDriver(capabilities);
driver.get("www.someurlexample.com");
try {
SOClass so = new SOClass(driver);
so.export(OUT_PATH);
} catch(Exception e) {
e.printStackTrace();
}
}
}
Now, barring any compilation issues (I made this up as an example) my code will catch any exceptions the SOClass is defined to throw. However, I was wondering if the table does not exist on the page and Selenium throws a NoSuchElementException, will my SOMain automatically catch this exception because of the
} catch(Exception e) {
}
block, or because the object is not specified to throw this error, SOMain will not handle this error and break?

Your catch will handle every exception that inherits from the Exception class (and occurs in the try obviously), which means, including NoSuchElementException as you can see here the hierarchy of it.
However, you need to distinguish Checked Exceptions and Unchecked Exceptions or Runtime Exceptions. As you can see NoSuchElementException extends java.lang.RuntimeException which means it's unchecked, therefore the compiler doesn't require you to handle it. But keep in mind that this runtime exception extends java.lang.Exception so your catch will catch it during runtime if it occurs.

Related

NullPointerException at FirefoxDriver instance [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am new to the automated tests so please, bear with me
I've been trying to execute this Selenium-generated test, but with no success. It seems that there is a problem with the Firefox Driver instantiation process. Here is a copy-paste of my Stack, followed by the test itself.
testUntitledTestCase caused an error: java.lang.NullPointerException
java.lang.NullPointerException
at SomaTeste.tearDown(SomaTeste.java:47)
It also seems that it never reaches the "driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS)". It proceeds to the "driver.quit()"(line 47) right after executing "driver = new FirefoxDriver()".
By analyzing a breakpoint placed on line 47 (which is the "driver.quit()" one), I've confirmed that the "driver" variable is set to null, which explains why i'm getting the "NullPointerException", but why is it not being initialized in the first place ? I can't seem to find an answer to this.
Does anyone have any idea on what might be causing this?
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import junit.framework.TestCase;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
import org.junit.Test;
import static org.junit.Assert.*;
public class SomaTeste{
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
baseUrl = "https://www.katalon.com/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testUntitledTestCase() throws Exception {
driver.get("http://localhost:8080/SomarParcelas/");
driver.findElement(By.name("p1")).click();
driver.findElement(By.name("p1")).clear();
driver.findElement(By.name("p1")).sendKeys("21");
driver.findElement(By.name("p2")).click();
driver.findElement(By.name("p2")).clear();
driver.findElement(By.name("p2")).sendKeys("12");
driver.findElement(By.name("calcular")).click();
driver.findElement(By.xpath("//h1")).click();
assertEquals("O resultado foi 33", driver.findElement(By.xpath("//h1")).getText());
}
#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;
}
}
}
I cannot comment, but it works fine for me when I ran your code in Eclipse on Windows with the chrome driver. However, when I use the firefox driver, it does exactly what you are saying. It turns out to be the selenium version I used. I was using 3.3.1, but 3.9.1 works fine.

How to call a method in every test which is in the base class and has a data provider in selenium

I have been trying to integrate browser stack with my selenium scripts. As part of which i have added desired capabilities in my 'getBrowser' method with data provider in the Base class. As i want to run my scripts in multiple browsers. The browsers list is in "getData" method in Base class.
How can i call the getBrowser method in my testcases and have the getData(browsers list) defined in only the base class. This what i have done and its not right. i have added my base class and the test script.
Base.getBrowser(Platform platform, String browserName, String browserVersion); this line is were i am stuck.
Any help would be appreciated. Thanks
package com.gale.precision.FundVisualizer.core;
import java.net.MalformedURLException;
import java.net.URL;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.annotations.DataProvider;
import org.openqa.selenium.Platform;
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.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
public class Base {
//public static WebDriver driver = null;
public static WebDriver driver;
public static String DriverPath = System.getProperty("user.dir") + "//" + "Drivers";
public static String DirectoryPath = System.getProperty("user.dir");
public static Properties prop = new Properties();
public static InputStream input = null;
public static final String USERNAME = "antonyprabhu1";
public static final String AUTOMATE_KEY = "xHRMpqxgD8sn3e3sr75s";
public static final String URL = "https://" + USERNAME + ":" + AUTOMATE_KEY + "#hub-cloud.browserstack.com/wd/hub";
#DataProvider(name = "EnvironmentDetails")
public static void getBrowser(Platform platform, String browserName, String browserVersion) throws MalformedURLException
{
DesiredCapabilities capability = new DesiredCapabilities();
capability.setPlatform(platform);
capability.setBrowserName(browserName);
capability.setVersion(browserVersion);
capability.setCapability("browserstack.debug", "true");
driver = new RemoteWebDriver(new URL(URL), capability);
try {
input = new FileInputStream(DirectoryPath + "//" + "config" + "//" + "app.properties");
prop.load(input);
} catch (IOException e) {
e.printStackTrace();
}
}
#DataProvider(name = "EnvironmentDetails", parallel = true)
public Object[][] getData() {
Object[][] testData = new Object[][] {
{
Platform.MAC, "chrome", "62.0"
}, {
Platform.WIN8,
"chrome",
"62.0"
}, {
Platform.WINDOWS,
"firefox",
"57"
}
};
return testData;
}
public static void closeBrowser() {
driver.quit();
}
}
package comparison;
import java.net.MalformedURLException;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.Platform;
import org.openqa.selenium.StaleElementReferenceException;
import org.openqa.selenium.WebElement;
import org.testng.Assert;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterTest;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import com.gale.precision.FundVisualizer.core.Base;
import com.gale.precision.FundVisualizer.core.ExtentReport;
import com.gale.precision.FundVisualizer.pageObject.Comparison;
import com.gale.precision.FundVisualizer.pageObject.InvestmentsSearch;
#SuppressWarnings("unused")
public class AddedInvestmentDisplay extends ExtentReport {
/*============================================================================================================================
Test case : Verify that already selected Investments for comparison does not show up
======================================================================================*/
#Test(testName = "Comparison: Verify an already selected Investment for comparison does not show up in search")
public void verifyAddedInvestmentDisplay() throws InterruptedException, MalformedURLException {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser(Platform platform, String browserName, String browserVersion);
InvestmentsSearch.login(Base.driver);
InvestmentsSearch.InvestmentsLink(Base.driver).click();
JavascriptExecutor jse = (JavascriptExecutor) Base.driver;
jse.executeScript("window.scrollBy(0,750)", "");
InvestmentsSearch.ViewResults(Base.driver).click();
for (int i = 0; i <= 2; i++)
{
try {
Comparison.firstCheckBox(Base.driver).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
//Base.clickingStaleElements(Comparison.firstCheckBox(Base.driver));
//Comparison.firstCheckBox(Base.driver).click();
for (int i = 0; i <= 2; i++)
{
try {
Comparison.analyzeOrCompare(Base.driver).click();
break;
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
Comparison.addInvestmentField(Base.driver).sendKeys("MFC027");
Comparison.firstSearchResult(Base.driver).click();
Comparison.addInvestmentField(Base.driver).sendKeys("MFC027");
Assert.assertEquals(Comparison.emptySearchResult(Base.driver).isDisplayed(), true);
}
#DataProvider(name = "EnvironmentDetails", parallel = true)
public Object[][] getData() {
Object[][] testData = new Object[][] {
{
Platform.MAC, "chrome", "62.0"
}, {
Platform.WIN8,
"chrome",
"62.0"
}, {
Platform.WINDOWS,
"firefox",
"57"
}
};
return testData;
}
#AfterClass
public void tearDown()
{
Base.closeBrowser();
}
}
I could resolve this issue by passing the parameters in the #test method
#Test(testName="Comparison: Verify adding an index in the comparison", dataProvider = "EnvironmentDetails",dataProviderClass = BrowsersDataProvider.class)
public void verifyAddingIndex(Platform platform, String browserName, String browserVersion) throws InterruptedException, MalformedURLException {
//test = extent.createTest(Thread.currentThread().getStackTrace()[1].getMethodName());
Base.getBrowser(platform,browserName,browserVersion);
InvestmentsSearch.login(Base.driver);
like

How to continue execution from where the excel stopped?

I am working with excel using selenium web driver where username and password is passed is taken from excel and passed to application,pass/fail status is written back to excel.During exceptions such as no element found etc the execution stops. How to continue execution from the point where it stopped in the excel. Following is my code:
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.UnreachableBrowserException;
public class Checkbox2 {
static WebDriver driver;
private static String filePath = "C:\\TEST DATA\\Users\\test.xlsx";
private static String sheetName = "Sheet1";
static File fl= new File(filePath);
public static void main(String[] args) throws InterruptedException, EncryptedDocumentException, InvalidFormatException
{
System.setProperty("webdriver.firefox.bin", "C:\\Users\\vijayab\\AppData\\Local\\Mozilla Firefox\\firefox.exe");
driver=new FirefoxDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.get("https://qa-bnymellon.correctnet.com/bnymellon/release10/me.get?DPS.home");
// driver.findElement(By.xpath("html/body/div[4]/div/div/div[1]/a[1]")).click();
try {
FileInputStream fis = new FileInputStream("C:\\Users\\vijayab\\Documents\\Work\\TEST DATA\\Users\\test.xlsx");
Workbook wb;
wb = WorkbookFactory.create(fis);
Sheet sheet = wb.getSheet("Sheet1");
for(int count=0;count<=sheet.getLastRowNum();count++)
{
Row row = sheet.getRow(count);
System.out.println("\n----------------------------");
System.out.println("Running test case " + count);
runTest(count, sheet, row.getCell(0).toString(),row.getCell(1).toString(),row,wb);
}
fis.close();
driver.close();// Closing the firefox driver instance
} catch (IOException e) {
System.out.println("Test data file not found");
}
}
public static void runTest(int count,Sheet sheet,String name,String mailid, Row row, Workbook wb) throws InterruptedException, InvalidFormatException, IOException
{
System.out.println("Inputing name: "+name+" and mailid: "+mailid);
driver.findElement(By.name("USERNAME")).sendKeys(name);
driver.findElement(By.name("PASSWORD")).sendKeys(mailid);
driver.findElement(By.name("SIGNIN")).click();
//driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
try{
if(driver.findElements(By.name("loginForm")).size() == 0){
System.out.println("Valid credentials"+count);
driver.findElement(By.name("DISCLAIMER")).click();
driver.findElement(By.id("ACCOUNTDOCUMENTS")).click();
driver.findElement(By.xpath("//*[contains(text(),'Account Profile')]")).click();
Thread.sleep(3000);
driver.switchTo().frame("FDX1");
driver.switchTo().frame("frame2-1");
Thread.sleep(4000);
driver.findElement(By.name("chk")).click();
driver.findElement(By.name("PROFILE_UPDATE")).click();
Alert alert = driver.switchTo().alert();
alert.accept();
driver.get("<logout url>");
int cellindex = 3;
WriteToFile.setExcelData(wb,filePath, sheetName, row.getRowNum(),cellindex, "PASS");
System.out.println("Inputted name: "+name+" and mailid: "+mailid);
Thread.sleep(2000);
}
else if(driver.findElements(By.name("loginForm")).size() == 0){
driver.findElement(By.name("loginForm")).isDisplayed();
System.out.println("Inputted name: "+name+" and mailid: "+mailid + "does not exist");
int cellindex = 3;
WriteToFile.setExcelData(wb,filePath, sheetName, row.getRowNum(),cellindex, "Fail");
return;
}
}
catch(UnreachableBrowserException e){
System.out.println("Exception occured");
}
}
}
There could be different ways to handle it. What i would suggest is below one.
Add another Catch block to catch Exceptions in method runTest. Return aBoolenvalue as false in case of exceptions. Based on the return type, decide on how to proceed further in you For Loop. I Guess this should help you solve the problem. Please let me know in case of any queries.

Java-Selenium2: How to fix the below exception in java code after exporting from selenium IDE

I am learning selenium and Java.
Trying to create a test script to book hotel, then view the itinerary and finally perform logout operation on a test site.
After clicking "book_now" button it takes some time to load the next frame/page where the itinerary button exists.
I explicitly added "waitForFrameToLoad" command as the test case was failing on IDE stating "my_Itinerary" element not found.
After addition test case passed on IDE and when exported using junit/webdriver option,I see the below note:
package com.example.tests;
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 CompleteBooking {
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 = "http://www.adactin.com/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testCompleteBooking() throws Exception {
driver.get(baseUrl + "/HotelAppBuild2/");
driver.findElement(By.id("username")).sendKeys("pranu86”);
driver.findElement(By.id("password")).sendKeys("test”);
driver.findElement(By.id("login")).click();
new Select(driver.findElement(By.id("hotels"))).selectByVisibleText("Hotel Sunshine");
driver.findElement(By.id("Submit")).click();
driver.findElement(By.id("radiobutton_0")).click();
driver.findElement(By.id("continue")).click();
driver.findElement(By.id("first_name")).sendKeys("pranu");
driver.findElement(By.id("cc_num")).sendKeys("1234567891234567");
new Select(driver.findElement(By.id("cc_type"))).selectByVisibleText("VISA");
driver.findElement(By.id("book_now")).click();
// ERROR: Caught exception [ERROR: Unsupported command [waitForFrameToLoad | http://www.adactin.com/HotelAppBuild2/BookingConfirm.php | 10000]]
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
driver.findElement(By.id("my_itinerary")).click();
// ERROR: Caught exception [unknown command [clickAndWait ]]
driver.findElement(By.linkText("Click here to login again")).click();}
}
#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;
}
}
How to fix this issue/Error note? Please help

Selenium null pointer exception, when trying to use constructor

I created a class which has page objects defined in it. Then I am trying to use that class in a test class by using a constructor. However when I run the test class using JUnit I am getting a NullPointerException error.
Page_Objects Class:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
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.support.ui.Select;
public class Page_Objects {
private WebDriver driver;
WebElement Username = driver.findElement(By.id("username"));
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
WebElement Password = driver.findElement(By.id("password"));
WebElement Login_Button = driver.findElement(By.id("Login"));
WebElement Logout_Button = driver.findElement(By.linkText("Logout"));
}
Test Class:
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 Salesforce_Test {
private WebDriver driver1;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
Page_Objects pageobjects = new Page_Objects();
#Before
public void setUp() throws Exception {
driver1 = new FirefoxDriver();
baseUrl = "some url for testing/";
driver1.navigate().to(baseUrl);
driver1.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void Login_Logout() throws Exception {
pageobjects.Username.sendKeys("someusername");
// ERROR: Caught exception [Error: locator strategy either id or name must be specified explicitly.]
pageobjects.Password.sendKeys("somepassword");
pageobjects.Login_Button.click();
pageobjects.Logout_Button.click();
}
#After
public void tearDown() throws Exception {
driver1.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver1.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver1.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver1.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
When I run the above class I get a null pointer exception.
java.lang.NullPointerException
at Page_Objects.<init>(Page_Objects.java:20)
at Salesforce_Test.<init>(Salesforce_Test.java:16)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
I see two issues here. First is that the Page_Objects class is called before you initiated the driver. That's why when you're calling
Page_Objects pageobjects = new Page_Objects();
you're getting a NullPointerException.
So you want to initiate the Page_Objects after you've initiated the driver.
Second, you need to pass it the instance of the driver you've initiated, because right now it has its own Private driver which isn't initiated and therefore it's null.
So in short:
Initiate Page_Objects after you've initiated driver (after the driver1 = new FirefoxDriver(); line)
Call it with the driver you've initiated: Page_Objects pageobjects = new Page_Objects(driver1 );

Categories

Resources