NullPointerException with custom ExpectedCondition - java

I created a custom ExpectedCondition to be used as input in my wait.until() method, however when my code reaches my custom ExpectedCondition argument, a NullPointerException is thrown, and I cannot figure out why. I've tried everything, and the same result is always received. Below, you will find my code
CustomWait:
public static ExpectedCondition<Boolean> visibilityOfElement(final
WebElement element) {
return new ExpectedCondition<Boolean>() {
#Override
public Boolean apply(WebDriver input) {
try {
return element.isDisplayed();
}catch(NoSuchElementException e) {
return false;
}catch(StaleElementReferenceException e1) {
return false;
}
}
};
}
}
LoginPage (this page contains the code that calls the CustomWait class method):
public class LoginPage {
WebDriver driver;
WebDriverWait wait;
#FindBy(how=How.ID, using="email") WebElement email;
#FindBy(how=How.ID, using="password") WebElement password;
#FindBy(how=How.ID, using="submit-button") WebElement loginSubmitButton;
public LoginPage(WebDriver driver) {
this.driver = driver;
}
public void login(String email, String password) {
wait.until(CustomWait.visibilityOfElement(this.email));
this.email.sendKeys(email);
this.password.sendKeys(password);
loginSubmitButton.click();
}
}
When the program reaches the code "wait.until(CustomWait.visibilityOfElement(this.email))", that is when the NullPointerException is thrown, and I believe that the "WebDriver input" part of my parameter for the visibilityOfElement method of the Custom Wait class is where the problem lies, but I cannot figure out why.
Main(this is where my test is found):
public class Main {
WebDriver driver;
public Main() {
driver = BrowserFactory.startBrowser("chrome",
"http://123help123.com/");
}
#Test
public void smokeTest() {
HomePage homePage = PageFactory.initElements(driver,
HomePage.class);
homePage.clickLogin();
LoginPage loginPage = PageFactory.initElements(driver,
LoginPage.class);
loginPage.login("haha", "123");
}
}
BrowserFactory (this is how my driver is created):
public class BrowserFactory {
static WebDriver driver;
public static WebDriver startBrowser(String browser, String url) {
if(browser.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();
}
else if(browser.equalsIgnoreCase("chrome")) {
if(SystemUtils.IS_OS_MAC_OSX) {
System.setProperty("webdriver.chrome.driver",
"src/chromedriver");
}
else if(SystemUtils.IS_OS_WINDOWS) {
System.setProperty("webdriver.chrome.driver",
"src/chromedriver.exe");
}
driver = new ChromeDriver();
}
else if(browser.equalsIgnoreCase("ie")) {
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
Any help is greatly appreciated, and if you need more information, then please let me know.

You got NullPointerException because you haven't initialized wait in your LoginPage class. So there is not driver to pass to your custom ExpectedCondition.
public LoginPage(WebDriver driver) {
this.driver = driver;
this.wait = new WebDriverWait(driver,5);
}

Related

How to switch between two or mutlple chrome browser windows (Not tabs) using selenium in java?

Here is code that I want to do switching. I do some stuff at user X and then again by calling openbrowser() method I login to user y and do some stuff now want to switch to X user chrome browser again for next actions.
public static void openbrowser() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "/home/chromedriver");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
public static void navigateAppUrl(int row, int column) throws Exception {
driver.get(excel.readData(row , column));
}
public static void LogintoXUser() {
//Do some stuff//
}
public static void LogintoYUser() {
//Do some stuff//
}
public static void main(String args[]){
openbrowser();
navigateAppUrl(1,2);
LogintoXUser()
// new chrome browser instance is created
openbrowser();
navigateAppUrl(1,2);
LogintoYUser()
}
Change method openbrowser() to WebDriver. You can create more instances of WebDriver and arbitrarily use them.
public static WebDriver openbrowser() {
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "/home/chromedriver");
WebDriver driver = new ChromeDriver(options);
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
return driver;
}
public static void main(String args[]){
WebDriver driver1 = openbrowser();
// do some staff with driver1
WebDriver driver2 = openbrowser();
// do some staff with driver2
// continue with some staff with driver1
driver1....
// continue with some staff with driver2
driver2....
}

Switching between browsers using Linktext in Selenium

This is how you can switch browsers pages using linkText in Selenium as below
public class locatorsPractice {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.gecko.driver","/path");
WebDriver driver =new FirefoxDriver();
driver.manage().window().maximize();
driver.navigate().to("https://browser url");
String strMainWindowHandle=driver.getWindowHandle();
System.out.println("Window title"+driver.getTitle());
driver.findElement(By.linkText("Google")).click();
Set <String> strHandles=driver.getWindowHandles();
for (String handle:strHandles) {
driver.switchTo().window(handle);
String strTitle=driver.getTitle();
if(strTitle.equalsIgnoreCase("Google")) {
System.out.println(driver.getTitle());
driver.manage().window().maximize();
Thread.sleep(2000);
driver.close();
}
}
}}

Getting "java.lang.NullPointerException" error which trying to call the a function to take screenshot in a test method on Selenium [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
java.lang.NullPointerException is appearing
(1 answer)
Getting error exception in thread "main" java.lang.NullPointerException
(2 answers)
java.lang.NullPointerException using static WebDriver instance
(1 answer)
Closed 2 years ago.
I am new to the selenium automation world, Getting java.lang.NullPointerException error which trying to call the function to take a screenshot in a test method on Selenium. I am pretty sure I have missed initialize or return the driver somewhere. below is the code.
baseTest class where I am initializing the webdriver
public class baseTest {
public Properties objProp = new Properties();
FileInputStream readProp;
{
try {
readProp = new FileInputStream("C:\\Users\\kiran\\IdeaProjects\\SelProject2\\src\\test\\java\\appDetails.properties");
objProp.load(readProp);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
protected WebDriver driver;
#BeforeClass
public void beforeSuite()
{
System.setProperty(objProp.getProperty("browser"),objProp.getProperty("driverPath"));
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(objProp.getProperty("URL"));
}
#AfterSuite
public void afterSuite()
{
if(null != driver)
{
driver.close();
driver.quit();
}
}
public WebDriver getDriver()
{
return driver;
}
}
All my tests extends the baseTest function link shown below
public class loginFunction extends baseTest {
guruLoginPage objLogin;
guruHomePage objHome;
takeScreenshot objSS = new takeScreenshot(driver);
//readExcel readObj;
#Test
public void performLogin() throws IOException, InterruptedException {
objLogin = new guruLoginPage(driver);
String loginPageTitle = objLogin.getTitle();
Assert.assertTrue(loginPageTitle.contains("Demo Site"));
objSS.screenshot();
objLogin.loginAction(objProp.getProperty("appUsername"), objProp.getProperty("appPassword"));
Thread.sleep(2000);
objHome = new guruHomePage(driver);
Assert.assertTrue(objHome.validateLogin().contains("Manger Id : mngr242657"));
Thread.sleep(2000);
objSS.screenshot();
}
}
when i write this piece of code in the loginfunction, it works fine, but when i am trying to optimize and put it in a separate class and call the method I am getting java.lang.NullPointerException error
public class takeScreenshot{
WebDriver driver;
public takeScreenshot(WebDriver driver)
{
this.driver=driver;
PageFactory.initElements(driver,this);
}
public void screenshot() throws IOException {
String fileSuffix = DateTime.now().toString("yyyy-dd-MM-HH-mm-ss");
TakesScreenshot ss = ((TakesScreenshot)this.driver);
File srcFile = ss.getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(srcFile,new File("C:\\Users\\kiran\\IdeaProjects\\SelProject2\\src\\test\\java\\Screenshots\\"+fileSuffix+".jpg"));
}
}

Proper way to pass a webdriver to another class

I want to pass my WebDriver to another class instead of passing it to the individual methods within that class. That would mean passing it to the constructor of the class when I create an instance of it. Here is my code, and my issue further below -
public class StepDefinitions{
public static WebDriver driver = null;
CustomWaits waits;
#Before("#setup")
public void setUp() {
driver = utilities.DriverFactory.createDriver(browserType);
System.out.println("# StepDefinitions.setUp(), driver = " + driver);
waits = new CustomWaits(driver);
}
}
public class CustomWaits {
WebDriver driver;
public CustomWaits(WebDriver driver){
this.driver = driver;
}
public boolean explicitWaitMethod(String id) {
boolean status = false;
try {
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
status = element.isDisplayed();
} catch (NullPointerException e){
e.printStackTrace();
}
return status;
}
}
The error I am getting in is NullPointerException when a method of that class is called within an #Given, #When, etc. This is a scope issue I cannot resolve.
Feature File:
#test
Feature: Test
#setup
Scenario: Navigate to Webpage and Assert Page Title
Given I am on the "google" Website
Then page title is "google"
Here is the step definition:
#Given("^element with id \"([^\"]*)\" is displayed$")
public void element_is_displayed(String link) throws Throwable {
if (waits.explicitWaitMethod(link)) {
// This is where waits becomes null when I put a breakpoint
driver.findElement(By.id(link)).isDisplayed();
} else {
System.out.println("Timed out waiting for element to display");
}
}
I would do something like this.
public class StepDefinitions{
public StepDefinitions() {
driver = utilities.DriverFactory.createDriver(browserType);
System.out.println("# StepDefinitions.setUp(), driver = " + driver);
waits = new CustomWaits(driver);
}
public static WebDriver driver = null;
public static CustomWaits waits;
#Given("^element with id \"([^\"]*)\" is displayed$")
public void element_is_displayed(String link) throws Throwable {
if (waits.explicitWaitMethod(link)) {
// This is where waits becomes null when I put a breakpoint
driver.findElement(By.id(link)).isDisplayed();
} else {
System.out.println("Timed out waiting for element to display");
}
}
}
public class CustomWaits {
private static WebDriver driver;
public CustomWaits(WebDriver driver){
this.driver = driver;
}
public boolean explicitWaitMethod(String id) {
boolean status = false;
try {
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id(id)));
status = element.isDisplayed();
} catch (NullPointerException e){
e.printStackTrace();
}
return status;
}
}

How to select a check box in selenium webdriver?

Can any one pls help me out
There are many check boxes available with values and I have to choose a particular value in check box. I dont know how to choose a check box value in selenium webdriver
https://www.blueshieldca.com/fap/app/search.html
This one works.. This will click the check box "General Medicine" under "Type" on left menu...
public class SampleUITest extends SeleneseTestBase {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
try {
driver.get("https://www.blueshieldca.com/fap/app/search.html");
driver.findElement(By.id("location"))
.sendKeys("Locans, Fresno, CA");
driver.findElement(By.className("findNow")).click();
Thread.sleep(1000);
driver.findElement(By.className("continueBtn")).click();
Thread.sleep(15000);
driver.findElement(
By.xpath("//ul[#id='doctortypesmodule']/li[2]/input"))
.click();
} catch (Exception e) {
e.printStackTrace();
} finally {
driver.quit();
}
}
}
This works!!
Your actual issue is with wait
#BeforeTest
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "https://www.blueshieldca.com/fap/app";
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
#Test
public void Test01() throws Exception {
WebDriverWait wait = new WebDriverWait(driver, 60);
driver.get(baseUrl + "/search.html");
driver.findElement(By.xpath("//input[#name='location']")).clear();
driver.findElement(By.xpath("//input[#name='location']")).sendKeys(
"Los Alamitos, Orange, CA");
driver.findElement(By.xpath("//input[#value='findNow']")).click();
Thread.sleep(3000);
driver.findElement(By.xpath("//input[#onclick='continueallPlans();']"))
.click();
wait.until(ExpectedConditions.elementToBeClickable(By
.xpath("//input[#onclick='javascript:results_OnProviderCompareClicked(this);']")));
List<WebElement> ele = driver
.findElements(By
.xpath("//input[#onclick='javascript:results_OnProviderCompareClicked(this);']"));
System.out.println(ele.size());
ele.get(0).click();
}
Prashanth Sams | seleniumworks.com

Categories

Resources