Cannt able to find Element in selenium - selenium-webdriver

My coding not find element. Pls anyone help me to come out of my mistake.
Testcase
#Test
public void main() throws Exception {
Thread.sleep(5000);
System.out.println("Before sign in action execution");
SignIn_Action.Execute(iTestCaseRow);
}
SignIn_Action
public class SignIn_Action{
public static void Execute(int iTestCaseRow) throws Exception{
// Fetch user name from Excel
String sUserName = ExcelUtils.getCellData(iTestCaseRow, Constant.col_UserName);
System.out.println("User Name read from --> "+ sUserName);
// Fetch password from Excel
String sPassword = ExcelUtils.getCellData(iTestCaseRow, Constant.col_Password);
System.out.println("Password read from excel --> "+ sPassword);
LoginPageObjects.txtbx_username().sendKeys(sUserName);
LoginPageObjects.txtbx_password().sendKeys(sPassword);
LoginPageObjects.btn_login().click();
}
LoginPageObject class
public class LoginPageObjects extends BaseClass {
private static WebElement element = null;
public LoginPageObjects(WebDriver driver){
super(driver);
}
public static WebElement txtbx_username(){
try {
WebElement element = null;
System.out.println("Inside txtbx_username method");
element = driver.findElement(By.name("first_name"));
System.out.println("Fetched element name is : "+element);
Log.info("Username text box found");
}catch (Exception e){
Log.error("UserName text box is not found on the Login Page");
throw(e);
}
return element;
}
}
}
BaseClass
public class BaseClass {
public static WebDriver driver;
public static boolean bResult;
public BaseClass(WebDriver driver){
BaseClass.driver = driver;
BaseClass.bResult = true;
}
}
My problem is in the below code
element = driver.findElement(By.name("first_name"));
This code is not find element and it shows below error message
java.lang.NullPointerException
at pageObjects.LoginPageObjects.txtbx_username(LoginPageObjects.java:27)

Related

Getting null pointer exception while open the url in selenium automation [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Here, I am using page object model and I want to pass the driver to other classes.But i am getting null pointer exception while launch the website (driver.get("")).
This is my base class
public class BaseClass {
public WebDriver driver;
public Logger logger = Logger.getLogger(Common.class.getPackage().getName());
public void startBrowser() {
if(driver == null) {
System.setProperty("webdriver.chrome.driver", "desktop/chromedriver.exe");
driver = new ChromeDriver();
}
}
public void quitBrowser() {
driver.quit();
}
}
and then this is my runner class:
public class TestRunnerTestNG extends AbstractTestNGCucumberTests {
BaseClass a;
#BeforeClass
public void launch()
{
a = new BaseClass();
a.startBrowser();
}
#AfterClass
public void tearBrowser()
{
a.quitBrowser();
}
}
Here, I am starting the browser using Beforeclass annotation and quit the browser using afterClass annotation.
and the following class is my page Object class: and here I have the method for launch the url:
public class SignIn extends BaseClass {
public SignIn(WebDriver driver) {
this.driver = driver ;
PageFactory.initElements(driver, this);
}
//Locators
#FindBy(id = "email")
private WebElement user_Email;
#FindBy(id = "password")
private WebElement user_Password;
#FindBy(xpath = "//span[text()='Sign In']")
private WebElement signIn_Btn;
public void landing()
{
driver.get("https://***************"); <<<< Here I am getting the null pointer exception.
}
public void signInPageGUI()
{
boolean checkSignInTextGUI = waitElement(signInText);
Assert.assertTrue(checkSignInTextGUI);
boolean CheckEmailField = waitElement(user_Email);
Assert.assertTrue(CheckEmailField);
boolean checkPwdField = waitElement(user_Password);
Assert.assertTrue(checkPwdField);
}
private void emailField(String emailName) {
user_Email.sendKeys(emailName);
}
private void passwordField(String password) {
user_Password.sendKeys(password);
}
}
and the final code is my step definition class and this is place I am calling the code.
public class LoginPage {
WebDriver driver ;
#Given("user landed to the yoco URL {string}")
public void landedOnYoCo(String string) {
System.out.println("print the string" +string);
System.out.println("driver value is " );
SignIn logIN = new SignIn(driver);
logIN.landing();
}
}
Here, Only I am calling the landing method to launch the website.
and The error is:
java.lang.NullPointerException
at pageObject.SignIn.landing(SignIn.java:83)
at stepDefs.LoginPage.landedOnYoCo(LoginPage.java:32)
at ✽.user landed to the yoco URL "https://my.yocoboard.com"(file:///Users/vinoth/Git/YoCoAutomation/src/test/resources/logIN.feature:7)
Call startBrowser before calling landing to initialize driver.
public void landedOnYoCo(String string) {
System.out.println("print the string" +string);
System.out.println("driver value is " );
SignIn logIN = new SignIn(driver);
logIN.startBrowser();
logIN.landing();
}

How to fix this NullPointerException with selenium and java?

I am trying to run my Automation script, I am launching URL but I am getting java.lang.NullPointerException
package lib.Page;
public class LoginPage {
public static final String URL = null;
public static final String TITLE = null;
public static final String EMAIL = null;
public static final String PASSWORD = null;
WebDriver driver;
WebDriverWait wait;
public LoginPage(WebDriver driver, WebDriverWait wait) {
this.driver = driver;
this.wait = wait;
}
public LoginPage lauchUrl(String url){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
driver.get(LoginPageData.URL);
return this;
Check your stack trace for the exact row where you are getting this error. My guess would be this:
driver.get(LoginPageData.URL);
as I don't see you initializing LoginPageData anywhere.

#FindBy error With class Select

I am trying to implement Page Object with annotation #FindBy in class Select. In Eclipse it's showing following a message:
the method id(String) in the type By is not applicable for the arguments (WebElement).
I do not why this message comes. Follow below the code and image of error.
Class FaturamentoGeTratamentoOsPage
public class FaturamentoGeTratamentoOsPage {
WebDriver driver;
#FindBy(id = "cboMotivo")
WebElement CBOMotivo;
public FaturamentoGeTratamentoOsPage(WebDriver driver) {
this.driver = driver;
}
public void preencherCampoMotivo(String CampoMotivo) {
// Campo Motivo
WebElement campoMotivo = driver.findElement(By.id(CBOMotivo));
Select slcMotivo = new Select(campoMotivo);
slcMotivo.selectByVisibleText(CampoMotivo);
}
public void preencherCampoSubmotivo(String CampoSubMotivo) throws Exception {
}
}
Class FaturamentoGeConectividadeFacilidadesTest
public class FaturamentoGeConectividadeFacilidadesTest {
static WebDriver driver;
#Before
public void setUp() throws Exception {
SelecionarNavegador nav = new SelecionarNavegador();
driver = nav.iniciarNavegador("chrome", "http://10.5.9.45/BkoMais_Selenium/");
}
#Test
public void selecionarFacilidades() throws Exception {
// Logando na aplicação
LogarBkoMaisPage login = new LogarBkoMaisPage(driver);
login.logar("844502", "Bcc201707");
// BackOffice >> FaturamentoGe >> Conectividade
FaturamentoGeConectividadeFacilidadesPage menu = new FaturamentoGeConectividadeFacilidadesPage(driver);
menu.logarFaturamentoGeConectividade();
//Registro >> Novo caso
RegistroNovoCasoPage reg = new RegistroNovoCasoPage(driver);
reg.registrarCaso();
//Preencher campos
FaturamentoGeTratamentoOsPage campo = new FaturamentoGeTratamentoOsPage(driver);
campo.preencherCampoMotivo(" Concluido ");
}
#After
public void tearDown() throws Exception {
Thread.sleep(5000);
driver.quit();
}
}
You need to add pagefactory.init to initialize webelement.
public FaturamentoGeTratamentoOsPage(WebDriver driver) { this.driver = driver;
PageFactory.initElements(driver, this);
}
No use of below line .. because CBOMotive directly returns you a webelement only
WebElement campoMotivo = driver.findElement(By.id(CBOMotivo));
You are getting the error because By.id() expects a String, not a WebElement. You have defined CBOMotivo as a WebElement but are treating it like a String.
The following is correct usage
WebElement campoMotivo = driver.findElement(By.id("cboMotivo"));
What you want is
public void preencherCampoMotivo(String CampoMotivo) {
// Campo Motivo
Select slcMotivo = new Select(CBOMotivo);
slcMotivo.selectByVisibleText(CampoMotivo);
}

Selenium POM java.lang.NullPointerException

I am getting "java.lang.NullPointerException" when I am trying to execute my test case based on POM.
The class BrowserFactory lets me choose a browser, the class Flipkart_Login based on POM stores all the element of that particular page and has a method for Valid_Login()
and finally Test_Flipkart_Login class - calls the Valid_Login() method for executon but when I try to execute this class, I get java.lang.NullPointerException.
Kindly advise!
FAILED: Flipkart_Login_Test
java.lang.NullPointerException
at DataProviders.ConfigDataProvider.getURL(ConfigDataProvider.java:31)
at TestCases.Test_Flipkart_Login.Flipkart_Login_Test(Test_Flipkart_Login.java:19)
public class ConfigDataProvider
{
static Properties pro;
public ConfigDataProvider()
{
File src = new File("C:\\Data\\Bimlesh\\Flipkart_HybridFramework\\Flipkart.Hybrid.FrameworkComplete\\Configuration\\Config.Properties");
try
{
FileInputStream fis = new FileInputStream(src);
pro = new Properties();
pro.load(fis);
} catch (Exception e)
{
System.out.println("The Config exception is :"+e.getMessage());
}
}
public static String getURL()
{
String URL = pro.getProperty("URL");
return URL;
}
public static String ChromePath()
{
String Chrome = pro.getProperty("Chromepath");
return Chrome;
}
public static String IEPath()
{
String IE = pro.getProperty("IEpath");
return IE;
}
}
public class BrowserFactory
{
static WebDriver driver;
public static WebDriver getBrowser(String BrowserName)
{
if(BrowserName.equalsIgnoreCase("Firefox"))
{
driver = new FirefoxDriver();
}
else if(BrowserName.equalsIgnoreCase("Chrome"))
{
System.setProperty("webdriver.chrome.driver", ConfigDataProvider.ChromePath());
driver = new ChromeDriver();
}
else if(BrowserName.equalsIgnoreCase("IE"))
{
System.setProperty("webdriver.ie.driver", ConfigDataProvider.IEPath());
driver = new InternetExplorerDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
return driver;
}
public void ShutDown(WebDriver driver)
{
driver.quit();
}
}
public class Flipkart_Login
{
WebDriver driver;
public Flipkart_Login(WebDriver driver)
{
this.driver=driver;
}
#FindBy(xpath="//a[text()='Log In']") WebElement Login_Click;
#FindBy(xpath="//input[#class='_2zrpKA' and #type='text']") WebElement Enter_Email;
#FindBy(xpath="//input[#class='_2zrpKA _3v41xv' and #type='password']") WebElement Enter_Pass;
#FindBy(xpath="//button[#type='submit' and #class='_3zLR9i _1LctnI _36SmAs']") WebElement Login_Button;
public void Valid_Login()
{
Login_Click.click();
Enter_Email.sendKeys("xxx#gmail.com");
Enter_Pass.sendKeys("xxx");
Login_Button.click();
}
}
public class Test_Flipkart_Login
{
WebDriver driver;
#Test
public void Flipkart_Login_Test()
{
driver = BrowserFactory.getBrowser("Firefox");
driver.get(ConfigDataProvider.getURL());
Flipkart_Login page1 = PageFactory.initElements(driver, Flipkart_Login.class);
page1.Valid_Login();
}
}
You have initialized Properties pro in the constructor of the COnfigDataProider but you are using a static call to getURL method from your test class. Thus pro will be null and not initialized. Remove static call and use the constructor or make pro to static and initialize in static block.

How to get page object relative to another page object in Selenium WebDriver

I'm looking for solution how to get page object relative to another object in Page Object Model for selenium webdriver
Code of my test:
class StartPage {
WebDriver driver;
public HomePage(driver) {
this.driver = driver;
}
#FindBy(xpath="//div[#class='widget']//a[text()='link text']")
WebElement linkInWidget;
public void clickLink() {
linkInWidget.click();
return PageFactory.initElements(driver, NextPage.class);
}
}
Next page
class NextPage {
WebDriver driver;
public HomePage(driver) {
this.driver = driver;
}
#FindBy(xpath="//div[#class='widget']//input[#type='button']")
WebElement buttonInWidget;
#FindBy(id = "Index")
WebElement index;
public void clickButton() {
buttonInWidget.click();
return PageFactory.initElements(driver, NextPage.class);
}
public String getText() {
return index.getText();
}
}
Configuration class
public class ConfigureTest{
protected WebDriver driver;
protected String baseUrl;
protected StartPage startPage;
protected NextPage nextPage ;
#BeforeSuite
public void setUp() {
baseUrl = "http://webapp.com/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#AfterSuite
public void tearDown() throws Exception {
driver.quit();
}
}
And class of my test
public class SomeTest extends ConfigureTest {
#Test
public void testLinkAndButton() throws Exception {
startPage = PageFactory.initElements(driver, SomePage.class);
driver.get(baseUrl);
nextPage = startPage.clickLink();
nextPage.clickButton();
String data = nextPage.getText();
}
}
In both classes FirstPage and NextPage i find elements by xpath which has same first part //div[#class='widget'] it mean that all elements like buttons and links are under this widget and i have same xpath for widgets in my all pages
Problem: if only xpath of my widget will be changed i must make changes in all page objects of my test
Question: Is in any way how to improve my test for more flexibility with usage like:
page().get(Widget.class, "Widget name").get(Button.class, "Button name").click
Update: I resolve part of this problem in such way:
I create classes of my UI elements with get methods which can return objects of any class:
Class of Widget object
public class widget{
WebDriver driver;
public widget (WebDriver driver) {
this.driver = driver;
}
// Find a single element
#FindBy(xpath="//div[#class='tsf-p']")
WebElement linkInWidget;
public void click() {
linkInWidget.click();
}
public <T> T get(Class<T> expectedPage, String uiclass){
return PageFactory.initElements(driver, expectedPage);
}
}
Class of Button object
public class Button {
WebDriver driver;
public Button (WebDriver driver) {
this.driver = driver;
}
#FindBy(name="btnG")
WebElement button;
public void click() {
button.click();
}
public <T> T get(Class<T> expectedPage){
return PageFactory.initElements(driver, expectedPage);
}
}
Class of HomePage
public class HomePage {
WebDriver driver;
public HomePage(WebDriver driver) {
this.driver = driver;
}
#FindBy(xpath="//div[#class='widget']//a[text()='']")
WebElement linkInWidget;
public void click() {
linkInWidget.click();
}
public <T> T get(Class<T> expectedPage, String name){
return PageFactory.initElements(driver, expectedPage);
}
}
My test
public class searchTest {
WebDriver driver;
#BeforeTest
public void setup() {
driver = new FirefoxDriver();
driver.get("https://www.google.com.ua/");
}
#Test
public void testUI() {
HomePage homePage = PageFactory.initElements(driver, HomePage.class);
widget widget = PageFactory.initElements(driver, widget.class);
homePage.get(widget.class).get(Input.class).setValue("yahoo");
homePage.get(widget.class).get(Button.class).click();
}
}
And a result is that we can compose any object by using our classes
homePage.get(widget.class).get(Input.class).setValue("yahoo");
But how to get element by it name or number for example:
homePage.get(widget.class, "Name").get(Input.class, 1).setValue("yahoo");
I have a public repository here where I have implemented PageObject and PageFactory concept with TestNG. You are probably looking for a better way to inherit BaseClasse. The common methods should be placed in BaseClass and available to all PageObjects through inheritance. I have everything placed in GitHub and it's too broad to implement here.

Resources