I want to use: Login_Page Login = PageFactory.initElements(driver, Login_Page.class); in a unique way in all steps.
When I use it for each step I have no problems, but on the contrary Java shows me the error: " Value driver is always 'null'".
I would also like to replace Thread.sleep (2000); for a better solution.
Here is my Code:
package stepdefs;
import Pages.Login_Page;
import cucumber.api.java.pt.Dado;
import cucumber.api.java.pt.Entao;
import cucumber.api.java.pt.Quando;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import java.util.concurrent.TimeUnit;
public class StepDefinitions {
WebDriver driver;
Login_Page Login = PageFactory.initElements(driver, Login_Page.class);
#Dado("^que que estou na pagina principal do Gmail\\.$")
public void que_que_estou_na_pagina_principal_do_Gmail () throws Exception
{
System.setProperty("webdriver.chrome.driver", "C:\\browsers\\chromedriver.exe");
driver = new ChromeDriver();
driver.navigate().to("https://www.gmail.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#Quando("^forneco as credenciais validas\\.$")
public void forneco_as_credenciais_validas () throws Exception {
// Login_Page Login = PageFactory.initElements(driver, Login_Page.class);
Login.setEmail("rbkamontana#gmail.com");
Login.ClickOnNextButton();
Thread.sleep(2000);
Login.setSenha("automation10");
Thread.sleep(3000);
Login.ClickOnEnterButton();
driver.manage().window().maximize();
Thread.sleep(3000);
}
#Entao("^posso ver que estou logado\\.$")
public void posso_ver_que_estou_logado () throws Exception {
driver.findElement(By.xpath("//*[#id=\"gb\"]/div[2]/div[3]/div[1]/div[2]/div/a/span")).click();
String stringAtual = driver.findElement(By.xpath("//*[#id=\"gb\"]/div[2]/div[4]/div[1]/div[2]/div[1]")).getText();
String StringEsperada = "Rebeka Montana";
Assert.assertTrue(stringAtual.contains(StringEsperada));
//driver.quit();
}
}
Instead of Thread.sleep you can use selenium WebDriverWait function by a Locator.
Ref:
https://seleniumhq.github.io/selenium/docs/api/java/org/openqa/selenium/support/ui/WebDriverWait.html
void waitForElement(By Locator){
WebDriverWait myWait = new WebDriverWait(myDriver, 20);
myWait.until(ExpectedConditions.visibilityOfElementLocated(Locator));
}
Try initiating this inside of a constructor instead:
public StepDefinitions(){
driver = new ChromeDriver();
Login = PageFactory.initElements(driver, Login_Page.class);
}
An instance method is initializing the driver field at runtime, which explains why things work inside the step definition method. The solution is deceptively simple: create a getter method for the page model:
public class StepDefinitions {
WebDriver driver;
Login_Page login;
private Login_Page getLoginPage() {
if (login == null) {
login = PageFactory.initElements(driver, Login_Page.class);
}
return login;
}
#Quando("^forneco as credenciais validas\\.$")
public void forneco_as_credenciais_validas () throws Exception {
Login_Page login = getLoginPage();
login.setEmail("rbkamontana#gmail.com");
login.ClickOnNextButton();
Thread.sleep(2000);
login.setSenha("automation10");
Thread.sleep(3000);
login.ClickOnEnterButton();
driver.manage().window().maximize();
Thread.sleep(3000);
}
Related
I have send a searchable keyword through send keys in search text field of youtube. But when the drop down emerge below search textfield, I am unable to store the dropdown items in List and click anyone of them. I am getting '0' as a result in printing list size.
package SomeBasicAutomationPractice;
import java.util.List;
import org.apache.*;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class Practice_dynamic_xpath {
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "G:\\VivekAutomationPractice\\src\\drivers\\chromedriver.exe");
WebDriver driver= new ChromeDriver();
driver.get("https://www.youtube.com/");
driver.manage().window().maximize();
Thread.sleep(5000);
driver.findElement(By.xpath("//input[#id='search']")).sendKeys("selenium");
List<WebElement> li=driver.findElements(By.xpath("//*[starts-with(#id,'sbse')]"));
System.out.println(li.size());
li.get(2).click();
}
}
Please try the below code my friend. If this code helps you then I request you to mark it as accepted. This is how Stackoverflow works my friend :)
static{
System.setProperty("webdriver.chrome.driver", "C:\\Users\\Sangeeta-Laptop\\Downloads\\chromedriver_win32 (3)\\chromedriver.exe");
}
WebDriver driver = new ChromeDriver();
String urlBase = "https://www.youtube.com";
#BeforeTest
public void beforeTest() {
driver.get(urlBase);
driver.manage().window().maximize();
}
#Test
public void test() throws InterruptedException {
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.findElement(By.xpath("//input[#id='search']")).sendKeys("selenium");
Thread.sleep(5000);
driver.findElement(By.xpath("//input[#id='search']")).sendKeys(Keys.SPACE);
Thread.sleep(5000);
List<WebElement> li=driver.findElements(By.xpath("//*[starts-with(#id,'sbse')]"));
Thread.sleep(5000);
System.out.println(li.size());
}
#org.testng.annotations.AfterTest
public void AfterTest() {
driver.quit();
}
}
Can you try this
driver.findElements(By.cssSelector("#results ol#search-results>li h3>a"));
I am creating Page Object Model for the first time using selenium and I came across the below error, while executing the code give below. Need help in figuring out what am I missing...
java.lang.NullPointerException at org.openqa.selenium.support.pagefactory.DefaultElementLocator.find
My Code for reference:
package Pages;
import org.openqa.selenium.*;
public class BaseClass {
public static WebDriver driver;
public static String URL1 = "https://math-dad.com";
public void setupWebDriver(String drivername)
{
if (drivername.equalsIgnoreCase("Chrome"))
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
driver =new ChromeDriver(options);
}
else if (drivername.equalsIgnoreCase("Fire Fox"))
{
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
driver =new FirefoxDriver(options);
}
}
public BaseClass()
{
System.out.println("Base Class Initiate");
}
}
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class HeaderPage extends BaseClass{
#CacheLookup
#FindBy(xpath = "//div[#class='navbar-header']")
public static WebElement LOGO;
public displayHeader()
{
System.out.println(driver.findElement(By.xpath("//div[#class='navbar-header']")).getText());
}
public HeaderPage()
{
PageFactory.initElements(driver,this);
}
}
public class testHeaderPage extends HeaderPage{
#BeforeTest
public void beforeTest()
{
System.out.println("Before Test");
setupWebDriver("Chrome");
driver.get(URL1);
driver.manage().window().maximize();
driver.manage().timeouts().pageLoadTimeout(40, TimeUnit.SECONDS);
}
#Test
public void test1HeaderLOGO()
{
displayHeader(); // this is succesful
String Actual = LOGO.getText(); // Fails from this statement
System.out.println("Header LOGO: "+Actual);
String expected = "Math Dad";
Assert.assertEquals(Actual, expected, "Invalid Header");
}
#AfterTest
public void afterTest() {
drive.close();
}
}
In HeaderPage Classs, I am able to use 'driver' directly, but declaration of Page Factory element is failing. Any help on this please?
Use #BeforeClass annotation with this method so that Before Test driver can be initialized. This method will then execute Before every test.
#BeforeClass
public void setupWebDriver(String drivername) {
if (drivername.equalsIgnoreCase("Chrome"))
{
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.chrome.driver", "C:\\Drivers\\chromedriver.exe");
driver =new ChromeDriver(options);
}
else if (drivername.equalsIgnoreCase("Fire Fox"))
{
FirefoxOptions options = new FirefoxOptions();
options.addArguments("--disable-notifications");
System.setProperty("webdriver.gecko.driver", "C:\\Drivers\\geckodriver.exe");
driver =new FirefoxDriver(options);
}
}
I had tried to create method and call it from another file to the main class but It won't work the error message said "java.lang.NullPointerException"
Main.class
Keywords kw = new Keywords();
#When("^gmailDD$")
public void gmailDD() throws Throwable{
WebDriverWait wait5s = new WebDriverWait(driver, 5);
String regis = "/html/body/div[2]/div[1]/div[5]/ul[1]/li[3]/a";
String dd = "/html/body/div[1]/div/footer/div/div/div[1]";
String empty = "/html/body/div[1]/div/footer";
kw.clickbyxpath(regis);
String handle= driver.getWindowHandle();
System.out.println(handle);
// Store and Print the name of all the windows open
Set handles = driver.getWindowHandles();
System.out.println("Log window id: "+handles);
driver.switchTo().window("6442450949");
kw.clickbyxpath(empty);
kw.clickbyxpath(dd);
}`
Method.class
WebDriver saddriver;
public void clickbyxpath (String xpathvalue) throws InterruptedException, IOException
{
WebDriverWait sad = new WebDriverWait(saddriver, 10);
//To wait for element visible
System.out.println(xpathvalue);
String x = xpathvalue;
sad.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(x)));
wowdriver.findElement(By.xpath(x)).click();
}
I had tried to do the same coding in the same file, It has no problem but when I move Method.class to the new file, error message said "java.lang.NullPointerException" but I can get "xpathvalue" value.
This Error occur because of it will not able to find your driver instance.
refer below code snippet. this is not cucumber example but you can get idea by this.
Method.class
package testing.framework;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Method {
public WebDriver driver;
WebElement _clickForSearch;
public Method(WebDriver driver) {
this.driver = driver;
}
public Method clickByXpath(String xpathValues) {
WebDriverWait wait = new WebDriverWait(driver, 10);
_clickForSearch = wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xpathValues)));
_clickForSearch.click();
return this;
}
}
Testing.class
package testing.framework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Testing {
public static WebDriver driver;
public static void main(String[] args) {
getWebDriver();
String xpathValues= "//div[#class='FPdoLc VlcLAe']//input[#name='btnK']";
Method m1 = new Method(driver);
m1.clickByXpath(xpathValues);
}
public static void getWebDriver() {
System.setProperty("webdriver.chrome.driver", "Your chrome driver path");
driver = new ChromeDriver();
driver.get("https://www.google.com");
}
}
You need to pass your driver instance to another.
So I would suggest you take the webdriver wait out of your method and instantiate it when instantiating your webdriver. I would then create methods like so:
Driver class
private final String USER_DIRECTORY = System.getProperty("user.dir");
private final int GLOBAL_TIMEOUT = 30;
private WebDriver webDriver;
private WebDriverWait webDriverWait;
public Driver(String browserName) {
this.browserName = browserName;
System.out.println(browserName);
switch (this.browserName.toUpperCase()) {
case "CHROME":
initializeChromeDriver();
break;
}
}
private void initializeChromeDriver() {
System.setProperty("webdriver.chrome.driver", USER_DIRECTORY.concat("\\drivers\\chromedriver.exe"));
webDriver = new ChromeDriver();
webDriver.manage().window().maximize();
webDriverWait = new WebDriverWait(webDriver, GLOBAL_TIMEOUT);
}
Click method
public void buttonClickByXpath(String xpath) {
try {
WaitForPreseneOfElement(xpath);
webDriver.findElement(By.xpath(xpath)).click();
} catch (Exception e) {
takeScreenshot();
AllureLog("Failed to click on the button object. Please check your xpath. | xpath used = " + xpath + "");
Assert.fail();
}
}
Test Class
Import your driver class
import Base.Driver;
Then you would need declair your driver class like so:
Driver driver;
Now you will have access to your method using
driver.buttonClickByXpath(//YourXpathHere)
The problem is "Method m1 = new Method(driver);" keyword,
I had coded this line outside the main method.
thank you very much, Sir
You can visit on makemytrip.com. Hover on "trips" and click on "cancel bookings".
Here is the code what I am trying to execute and don't know where am I going wrong.
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver",
".\\exeFile\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.manage().window().maximize();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
driver.navigate().to("https://www.makemytrip.com/");
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
List<WebElement> dd_values=driver.findElements(By.xpath("//li[#class='menu-
trigger']//ul[#class='ch__profileOverlayTabs ch__capitalize
append_bottom20']//li"));
for (WebElement elements: dd_values) {
System.out.println("values of each attribute :
"+elements.getAttribute("innerHTML"));
if (elements.getAttribute("innerHTML").contains("Cancel Bookings")) {
elements.click();
break;
}
You have to perform the mouse hover action using Actions class and then need to perform the required action as below
Working Code:
driver.get("https://www.makemytrip.com/");
driver.manage().window().maximize();
//Explicit wait is added after the Page load
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.titleContains("Make"));
WebElement element=driver.findElement(By.xpath("//div[#class='ch__userInteraction ch__clearfix']//span[text()='trips']"));
Actions builder=new Actions(driver);
builder.moveToElement(element).build().perform();
driver.findElement(By.xpath("//div[#class='my_trips log-in-trip ch_trip_logged header-dropdown']//a[text()='Cancel Bookings']")).click();
Below is the code :
package com.demo.core;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.HasInputDevices;
import org.openqa.selenium.interactions.Mouse;
import org.openqa.selenium.interactions.internal.Locatable;
public class MakeMyTripDemo {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "J:\\STADIUM\\selenium-demo\\src\\main\\resources\\drivers\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.navigate().to("https://www.makemytrip.com/");
WebElement trips = driver.findElement(By.xpath("//a[#mt-class='trips_icon']"));
mouseOverElement(driver, trips);
WebElement cancelBooking = driver.findElement(By.xpath("//a[#id='ch_trips_cancel']"));
jsPress(driver, cancelBooking);
}
private static void mouseOverElement(WebDriver driver, WebElement webElement) {
Mouse mouse = ((HasInputDevices) driver).getMouse();
mouse.mouseMove(((Locatable) webElement).getCoordinates());
}
public static void jsPress(WebDriver driver, WebElement element) {
JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript("arguments[0].click();", element);
}
}
Hope it helps you. It is working.
In the below code on 33rd line getting below error message near wait.until
Multiple markers at this line
- The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files
- The method until(Function) in the type FluentWait is not applicable for the
arguments (ExpectedCondition)
package MPA;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginhelperClass {
WebDriver driver;
#FindBy(xpath = "//input[#ng-model='login.username']")
private WebElement userName;
#FindBy(xpath = "//input[#type='password']")
private WebElement Password;
#FindBy(xpath = "//input[#type='submit' and #value='Sign In']")
private WebElement SignIn;
#FindBy(xpath = "//span[#class='icon-avatar-round']")
private WebElement Avatar;
public LoginhelperClass(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void logIn(String uName, String Pswd) throws InterruptedException {
WebDriverWait wait=new WebDriverWait(driver,7);
wait.until(ExpectedConditions.visibilityOf(userName));
userName.sendKeys(uName);
Password.sendKeys(Pswd);
SignIn.click();
try {
Thread.sleep(4000);
if (Avatar.isDisplayed()) {
System.out.println("Login Successfull: " + uName);
} else {
System.out.println("Login failure check the credentials: " + uName);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
package MPA;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginhelperClass {
WebDriver driver;
#FindBy(xpath = "//input[#ng-model='login.username']")
private WebElement userName;
#FindBy(xpath = "//input[#type='password']")
private WebElement Password;
#FindBy(xpath = "//input[#type='submit' and #value='Sign In']")
private WebElement SignIn;
#FindBy(xpath = "//span[#class='icon-avatar-round']")
private WebElement Avatar;
public LoginhelperClass(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void logIn(String uName, String Pswd) throws InterruptedException {
WebDriverWait wait=new WebDriverWait(driver,7);
wait.until(ExpectedConditions.visibilityOf(userName));
userName.sendKeys(uName);
Password.sendKeys(Pswd);
SignIn.click();
try {
Thread.sleep(4000);
if (Avatar.isDisplayed()) {
System.out.println("Login Successfull: " + uName);
} else {
System.out.println("Login failure check the credentials: " + uName);
}
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
The error which you are seeing is as follows :
Multiple markers at this line - The type com.google.common.base.Function cannot be resolved. It is indirectly referenced from required .class files - The method until(Function) in the type FluentWait is not applicable for the arguments (ExpectedCondition)
Let us analyze what is happening in our code.
In the Page Object you have defined an WebElement as :
#FindBy(xpath = "//input[#ng-model='login.username']")
private WebElement userName;
Moving ahead you have tried to use the WebElement within the method :
public void logIn(String uName, String Pswd) throws InterruptedException {
WebDriverWait wait=new WebDriverWait(driver,7);
wait.until(ExpectedConditions.visibilityOf(userName));
//
}
So basically here we were trying to wait for the visibility of an Indirectly Referenced Angular WebElement userName which is dependent on the attribute ng-model. In such circumstances we can never be sure that when the WebElement will be referenced within a method userName will mandatory reference to a not NULL value. It may be NULL as well.
Now let us have a look at the Method Defination of visibilityOf, it is defined as :
visibilityOf(WebElement element)
An expectation for checking that an element, known to be present on the DOM of a page, is visible.
So clearly, visibilityOf method expects a Direct Reference of the WebElement. Hence in absence of a definite value (not NULL) of userName, WebDriverWait which is a variant of FluentWait shows the error.
Play with conditions with By/WebElement:
ExpectedConditions.presenceOfAllElementsLocatedBy(By)
ExpectedConditions.elementExists(By)
ExpectedConditions.elementIsVisible(By)
ExpectedConditions.elementToBeClickable(By/WebElement)
ExpectedConditions.visibilityOfAllElementsLocatedBy(By)