NullPointerException #FindBy in PageObjectModel using ChromeDriver and Chrome through Selenium - java

I am trying to implement PageObjectModel in Selenium. But I am getting NullPointer Exception at #FindBy. I hope someone can help me to identify my mistake. I created my Base class which sets config.properties file(it contains url,driver parameters) as well sets up driver. HomePage has object repository as well as actions and PageFactory is initialized. HomePageTest has all the tests. When I run the code, website is launched successfully. First test executes successfully. But at the second test it fails at FindBy.
Here is my code for reference.
Following is my Base class:
package com.seleniumEasy.qa.base;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
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.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import com.seleniumEasy.qa.commonUtility.*;
public class Base {
public static WebDriver driver;
public static Properties prop;
#BeforeClass
public void setBaseline()
{
try {
setProperties("\\Devp\\SeleniumEasy_Maven_POM_DataDrivenProject\\src\\main\\java\\com\\seleniumEasy\\qa\\config\\config.properties");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//setProperties("\\Devp\\SeleniumEasy_Maven_POM_DataDrivenProject\\src\\main\\java\\com\\seleniumEasy\\qa\\config\\config.properties");
setDriver();
}
/*#AfterClass
public void tearDown()
{
driver.quit();
}*/
public static void setProperties(String sFilePath) throws IOException
{
prop = new Properties();
FileInputStream fip = new FileInputStream(sFilePath);
prop.load(fip);
}
public static void setDriver()
{
switch(prop.getProperty("browser").toLowerCase())
{
case "chrome":
System.setProperty(prop.getProperty("chromekey"),prop.getProperty("chromedriverpath"));
driver = new ChromeDriver();
break;
case "firefox":
System.setProperty(prop.getProperty("firefoxkey"), prop.getProperty("firefoxdriverpath"));
driver = new FirefoxDriver();
break;
case "ie":
System.setProperty(prop.getProperty("iekey"),prop.getProperty("iedriverpath"));
driver = new InternetExplorerDriver();
break;
case "edge":
System.setProperty(prop.getProperty("edgekey"), prop.getProperty("edgedriverpath"));
driver = new EdgeDriver();
break;
default:
System.out.println("Driver does not exists: "+ prop.getProperty("browser"));
}
driver.manage().timeouts().implicitlyWait(commonUtil.Implicit_Wait, TimeUnit.SECONDS);
//driver.manage().timeouts().pageLoadTimeout(commonUtil.PageLoad_Wait,TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
//driver.manage().window().maximize();
if(driver.findElement(By.partialLinkText("No, thanks!")).isDisplayed())
driver.findElement(By.partialLinkText("No, thanks!")).click();
}
}
Following is my Page file
package com.seleniumEasy.qa.pages;
import java.util.ArrayList;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.seleniumEasy.qa.base.Base;
public class HomePage extends Base {
#FindBy(xpath="//*[#id=\"navbar-brand-centered\"]/ul[1]/li[1]/a")
WebElement InputForm;
#FindBy(css="#navbar-brand-centered > ul:nth-child(1) > li.dropdown.open")
List<WebElement> InputFormLst;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:first-of-type")
WebElement simpleFormDemo;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(2)")
WebElement checkBoxDemo;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(3)")
WebElement radioBtnDemo;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(4)")
WebElement dropDownLstDemo;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(5)")
WebElement inputFrmSubmit;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(6)")
WebElement ajaxForm;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(6)")
WebElement jQuerySelect;
List<WebElement> inputFormList = new ArrayList();
public HomePage()
{
PageFactory.initElements(driver, this);
}
public String validateTitle()
{
return driver.getTitle();
}
public SimpleForm validateSimpleFormDemo()
{
InputForm.click();
//driver.findElement(By.cssSelector("div.navbar-collapse.collapse.in>ul.nav.navbar-nav>li.dropdown.open>a")).click();
//driver.findElement(By.xpath("//*[#id=\"navbar-brand-centered\"]/ul[1]/li[1]/a")).click();
simpleFormDemo.click();
return new SimpleForm();
}
}
Following is my Test Page
package com.seleniumEasy.qa.Test;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import com.seleniumEasy.qa.base.Base;
import com.seleniumEasy.qa.pages.HomePage;
import com.seleniumEasy.qa.pages.SimpleForm;
public class HomePageTest extends Base {
HomePage homePage;
SoftAssert softAssert;
public HomePageTest()
{
homePage = new HomePage();
softAssert = new SoftAssert();
}
#Test(priority=1)
public void validateLoginPage()
{
String sTitle = homePage.validateTitle();
softAssert.assertEquals(sTitle, "Selenium Easy Demo");
}
#Test(priority=1)
public void validateSimpleForm()
{
SimpleForm simpleForm = homePage.validateSimpleFormDemo();
}
}
And here is the stacktrace
Starting ChromeDriver 2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e) on port 32000
Only local connections are allowed.
[1599758981.703][WARNING]: Timed out connecting to Chrome, retrying...
Sep 10, 2020 10:59:43 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\Default suite\Default test.xml
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\Default suite exists: true
FAILED: validateSimpleForm
java.lang.NullPointerException
at org.openqa.selenium.support.pagefactory.DefaultElementLocator.findElement(DefaultElementLocator.java:69)
at org.openqa.selenium.support.pagefactory.internal.LocatingElementHandler.invoke(LocatingElementHandler.java:38)
at com.sun.proxy.$Proxy8.click(Unknown Source)
at com.seleniumEasy.qa.pages.HomePage.validateSimpleFormDemo(HomePage.java:66)
at com.seleniumEasy.qa.Test.HomePageTest.validateSimpleForm(HomePageTest.java:39)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:100)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:646)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:811)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1129)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:129)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:112)
at org.testng.TestRunner.privateRun(TestRunner.java:746)
at org.testng.TestRunner.run(TestRunner.java:600)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:366)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:361)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:319)
at org.testng.SuiteRunner.run(SuiteRunner.java:268)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1264)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1189)
at org.testng.TestNG.runSuites(TestNG.java:1104)
at org.testng.TestNG.run(TestNG.java:1076)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:126)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:152)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:57)
===============================================
Default test
Tests run: 1, Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 1, Skips: 0
===============================================
[TestNG] Time taken by org.testng.reporters.EmailableReporter2#42d3bd8b: 8 ms
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\testng-failed.xml
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\Default suite\testng-failed.xml
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\Default suite exists: true
[TestNG] Time taken by [FailedReporter passed=0 failed=0 skipped=0]: 9 ms
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\toc.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\Default test.properties
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\index.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\main.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\groups.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\classes.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\reporter-output.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\methods-not-run.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite\testng.xml.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\Default suite exists: true
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old\index.html
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\old exists: true
[TestNG] Time taken by org.testng.reporters.SuiteHTMLReporter#6cd8737: 41 ms
[TestNG] Time taken by org.testng.reporters.jq.Main#6aaa5eb0: 46 ms
[Utils] Attempting to create C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\junitreports\TEST-com.seleniumEasy.qa.Test.HomePageTest.xml
[Utils] Directory C:\Arundhati\Devp\SeleniumEasy_Maven_POM_DataDrivenProject\test-output\junitreports exists: true
[TestNG] Time taken by org.testng.reporters.JUnitReportReporter#3b81a1bc: 6 ms
[TestNG] Time taken by org.testng.reporters.XMLReporter#6b2fad11: 12 ms
Here is the eclipse view

This error message...
Starting ChromeDriver 2.41.578737 (49da6702b16031c40d63e5618de03a32ff6c197e) on port 32000
Only local connections are allowed.
[1599758981.703][WARNING]: Timed out connecting to Chrome, retrying...
Sep 10, 2020 10:59:43 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
...implies that the ChromeDriver was unable to initiate/spawn a new Browsing Context i.e. Chrome Browser session.
Your main issue is the incompatibility between the version of the binaries you are using as follows:
You are using chromedriver=2.41
Release Notes of chromedriver=2.41 clearly mentions the following :
Supports Chrome v67-69
Possibly you are using the latest chrome=85.0
Release Notes of ChromeDriver v85.0 clearly mentions the following :
Supports Chrome version 85
So there is a clear mismatch between ChromeDriver v2.41 and the Chrome Browser v85.0
Solution
Ensure that:
JDK is upgraded to current levels JDK 8u252.
Selenium is upgraded to current released Version 3.141.59.
ChromeDriver is updated to current ChromeDriver v84.0 level.
Chrome is updated to current Chrome Version 85.0 level. (as per ChromeDriver v85.0 release notes)
If your base Web Client version is too old, then uninstall it and install a recent GA and released version of Web Client.
Clean your Project Workspace through your IDE and Rebuild your project with required dependencies only.
Take a System Reboot.
Execute your #Test as non-root user.
Always invoke driver.quit() within tearDown(){} method to close & destroy the WebDriver and Web Client instances gracefully.

Finally I found a solution to my own problem. NullPointerException is thrown when the driver object is null when the PageFactory is initialized.
The problem was before initializing the driver object I was calling PageFactory Initialization method. Thats why at the HomePage.java page in the constructor, driver was null.
Here is the updated code.
This is my Base class. I am initializing the cofig.properties file through the Base class constructor.
/**
*
*/
package com.seleniumEasy.qa.base;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
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.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import com.seleniumEasy.qa.commonUtility.*;
public class Base {
public static WebDriver driver;
public static Properties prop;
public WebDriver getDriver()
{
return driver;
}
public Base()
{
try
{
setProperties("\\Arundhati\\Devp\\SeleniumEasy_Maven_POM_DataDrivenProject\\src\\main\\java\\com\\seleniumEasy\\qa\\config\\config.properties");
} catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*#AfterClass
public void tearDown()
{
driver.quit();
}*/
public static void setProperties(String sFilePath) throws IOException
{
prop = new Properties();
FileInputStream fip = new FileInputStream(sFilePath);
prop.load(fip);
}
public static void setDriver()
{
if(prop.getProperty("browser").toLowerCase().equals("chrome"))
{
System.setProperty(prop.getProperty("chromekey"),prop.getProperty("chromedriverpath"));
driver = new ChromeDriver();
}
else if(prop.getProperty("browser").toLowerCase().equals("firefox"))
{
System.setProperty(prop.getProperty("firefoxkey"), prop.getProperty("firefoxdriverpath"));
driver = new FirefoxDriver();
}
else if(prop.getProperty("browser").toLowerCase().equals("ie"))
{
System.setProperty(prop.getProperty("iekey"),prop.getProperty("iedriverpath"));
driver = new InternetExplorerDriver();
}
else if(prop.getProperty("browser").toLowerCase().equals("edge"))
{
System.setProperty(prop.getProperty("edgekey"), prop.getProperty("edgedriverpath"));
driver = new EdgeDriver();
}
else
{
System.out.println("Driver does not exists: "+ prop.getProperty("browser"));
}
driver.manage().timeouts().implicitlyWait(commonUtil.Implicit_Wait, TimeUnit.SECONDS);
//driver.manage().timeouts().pageLoadTimeout(commonUtil.PageLoad_Wait,TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
//driver.manage().window().maximize();
if(driver.findElement(By.partialLinkText("No, thanks!")).isDisplayed())
driver.findElement(By.partialLinkText("No, thanks!")).click();
}
public String getProperty(String key)
{
return prop.getProperty(key);
}
}
Following is code for my HomePage.java. No change in this file.
/**
*
*/
package com.seleniumEasy.qa.pages;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import com.seleniumEasy.qa.base.Base;
public class HomePage extends Base {
#FindBy(xpath="//*[#id=\"navbar-brand-centered\"]/ul[1]/li[1]/a")
WebElement InputForm;
#FindBy(css="#navbar-brand-centered > ul:nth-child(1) > li.dropdown.open")
List<WebElement> InputFormLst;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:first-of-type")
WebElement simpleFormDemo;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(2)")
WebElement checkBoxDemo;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(3)")
WebElement radioBtnDemo;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(4)")
WebElement dropDownLstDemo;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(5)")
WebElement inputFrmSubmit;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(6)")
WebElement ajaxForm;
#FindBy(css="ul.nav.navbar-nav>li.dropdown.open>ul.dropdown-menu>li:nth-child(6)")
WebElement jQuerySelect;
//List<WebElement> inputFormList = new ArrayList();
public HomePage()
{
PageFactory.initElements(driver, this);
}
public String validateTitle()
{
return driver.getTitle();
}
public SimpleForm validateSimpleFormDemo()
{
InputForm.click();
simpleFormDemo.click();
return new SimpleForm();
}
}
Here is my HomePageTest file. I am calling the driver setup method following by creating the HomePage object in the BeforeClass annotation. No constructor in this class.
//package com.seleniumEasy.qa.testdata;
package com.seleniumEasy.qa.Test;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import com.seleniumEasy.qa.base.Base;
import com.seleniumEasy.qa.pages.HomePage;
import com.seleniumEasy.qa.pages.SimpleForm;
public class HomePageTest extends Base {
HomePage homePage;
SoftAssert softAssert;
#BeforeClass
public void setUp()
{
setDriver();
homePage = new HomePage();
//PageFactory.initElements(driver, HomePage.class);
softAssert = new SoftAssert();
}
/*#AfterClass
public void tearDown()
{
driver.quit();
}*/
#Test(priority='b')
public void validateLoginPage()
{
String sTitle = homePage.validateTitle();
softAssert.assertEquals(sTitle, "Selenium Easy Demo");
}
#Test(priority='a')
public void validateSimpleForm()
{
SimpleForm simpleForm = homePage.validateSimpleFormDemo();
}
}

Related

org.testng.TestNGException : Cannot instantiate class

I am facing this 'Cannot insantiate class' error on running one of my test cases in selenium webdriver using java(Using Maven project).
Below is the parent class where I defined driver and properties
package com.pvi.qa.base;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestBase {
public static WebDriver driver;
public static Properties prop ;
public TestBase() {
try {
prop = new Properties();
FileInputStream ip = new FileInputStream(System.getProperty("C:\\Users\\RxLogix\\eclipse-workspace\\PviIntake\\src\\main\\java\\com\\pvi\\qa\\config\\config.properties"));
prop.load(ip);
}
catch(FileNotFoundException e) {
e.printStackTrace();
}
catch(IOException e) {
e.printStackTrace();
}
}
public static void initialization () {
String BrowserName = prop.getProperty("browser");
if(BrowserName.equals("chrome")) {
System.setProperty("webdriver.chrome.driver", "D:\\Softwares\\chromedriver_win32 (1)\\chromedriver.exe");
driver = new ChromeDriver();}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().pageLoadTimeout(20, TimeUnit.SECONDS);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get(prop.getProperty("url"));
}
}
Below is the test cases class which I am running through TestNG
package com.pvi.qa.testcases;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.pvi.qa.base.TestBase;
import com.pvi.qa.pages.HomePage;
import com.pvi.qa.pages.LoginPage;
public class LoginPageTest extends TestBase{
LoginPage loginPage;
HomePage homePage;
public LoginPageTest() {
super();
}
#BeforeMethod
public void setUp() {
initialization();
loginPage = new LoginPage();
}
#Test
public void logintest() {
homePage = loginPage.login(prop.getProperty("username"), prop.getProperty("password"));
}
#AfterMethod
public void tearDown() {
driver.quit();
}
}
And below is the error I am getting -
[RemoteTestNG] detected TestNG version 6.14.3
org.testng.TestNGException:
Cannot instantiate class com.pvi.qa.testcases.LoginPageTest
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:30)
at org.testng.internal.ClassHelper.createInstance1(ClassHelper.java:423)
at org.testng.internal.ClassHelper.createInstance(ClassHelper.java:336)
at org.testng.internal.ClassImpl.getDefaultInstance(ClassImpl.java:125)
at org.testng.internal.ClassImpl.getInstances(ClassImpl.java:190)
at org.testng.TestClass.getInstances(TestClass.java:95)
at org.testng.TestClass.initTestClassesAndInstances(TestClass.java:81)
at org.testng.TestClass.init(TestClass.java:73)
at org.testng.TestClass.<init>(TestClass.java:38)
at org.testng.TestRunner.initMethods(TestRunner.java:389)
at org.testng.TestRunner.init(TestRunner.java:271)
at org.testng.TestRunner.init(TestRunner.java:241)
at org.testng.TestRunner.<init>(TestRunner.java:192)
at org.testng.remote.support.RemoteTestNG6_12$1.newTestRunner(RemoteTestNG6_12.java:33)
at org.testng.remote.support.RemoteTestNG6_12$DelegatingTestRunnerFactory.newTestRunner(RemoteTestNG6_12.java:66)
at org.testng.SuiteRunner$ProxyTestRunnerFactory.newTestRunner(SuiteRunner.java:713)
at org.testng.SuiteRunner.init(SuiteRunner.java:260)
at org.testng.SuiteRunner.<init>(SuiteRunner.java:198)
at org.testng.TestNG.createSuiteRunner(TestNG.java:1295)
at org.testng.TestNG.createSuiteRunners(TestNG.java:1273)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1128)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:114)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Caused by: java.lang.reflect.InvocationTargetException
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.base/java.lang.reflect.Constructor.newInstance(Unknown Source)
at org.testng.internal.ObjectFactoryImpl.newInstance(ObjectFactoryImpl.java:24)
... 25 more
Caused by: java.lang.NullPointerException
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at java.base/java.io.FileInputStream.<init>(Unknown Source)
at com.pvi.qa.base.TestBase.<init>(TestBase.java:20)
at com.pvi.qa.testcases.LoginPageTest.<init>(LoginPageTest.java:17)
... 30 more
I have tried everything but not worked for me, Please let me know why I am getting this error. Thanks
The lowest 'caused by' section points you to the underlying exception in your base class constructor: you are calling System.getProperty with a file path; that will probably return null. To me it looks like the whole call shouldn't be there, and you just want to pass the file path to the FileInputStream constructor (or read it from a system property with some key)
Looking at the code, I understand the issue is in the constructor of the base class.
LoginPageTest calls super() which invokes TestBase.
FileInputStream needs a file path. I suspect FileInputSteam object created is coming as null.
Why are you calling System.getProperty? Is the config.properties file available?
Just Remove System.getproperty from your base class. Use this lines of code
prop = new Properties();
FileInputStream ip = new FileInputStream(("C:\\Users\\RxLogix\\eclipse-workspace\\PviIntake\\src\\main\\java\\com\\pvi\\qa\\config\\config.properties"));
prop.load(ip);

Unable to perform simple click operation using appium code on Android app

I am new to Appium and I was trying to execute a simple program which performs a click operation. But the click operation is not happening. Here is the code:
package com.android.touchactionss;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.remote.DesiredCapabilities;
import io.appium.java_client.android.AndroidDriver;
public class Sample {
public static void main(String[] args) throws InterruptedException, MalformedURLException {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("platformName", "Android");
cap.setCapability("deviceName", "xiaomi-2014818-204648717d62");
cap.setCapability("version", "5.1.1");
cap.setCapability("appActivity", "com.mediamushroom.copymydata.app.EasyMigrateActivity");
cap.setCapability("appPackage", "com.mediamushroom.copymydata");
AndroidDriver<?> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
Thread.sleep(5000);
try{
System.out.println("STARTED");
driver.findElementByAndroidUIAutomator(
"new UiSelector().resourceId(\"com.mediamushroom.copymydata:id/NextButton\")");
//driver.findElement(By.id("//*[#resource-id='com.mediamushroom.copymydata:id/NextButton']"));
System.out.println("ENDED");
}
catch(Exception exception){
exception.printStackTrace();
}
Thread.sleep(5000);
driver.quit();
}
}
No exception is thrown but the click operation didn't happen. I tried with both driver.findElement(By.id("")) and driver.findElementByAndroidUIAutomator() method. But none of them worked. I have attached the object properties screen.
Versions used: appium software version 1.6.2
appium java_client version 6.1.0
selenium 3.13
First, add the following import:
import io.appium.java_client.android.AndroidElement;
Next change your code:
AndroidDriver<?> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
to:
AndroidDriver<AndroidElement> driver = new AndroidDriver<AndroidElement>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
You might need to change the URL to 0.0.0.0 but it depends on what your Appium Server settings are. They may be correct they way it is now.
Lastly, you need to use the following method to click the element:
driver.findElement(By.id("com.mediamushroom.copymydata:id/NextButton")).click();
Hi here is example in next few lines, try to use some testing framework, Junit, TestNg, I've removed main, used TestNG with this example:
Start Appium server:
Appium GUI (https://github.com/appium/appium-desktop/releases/tag/v1.6.2)
Appium via console : appium --address 127.0.0.1 --port 4723
when Appium server is up-an-running, call this code:
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.net.MalformedURLException;
import java.net.URL;
public class TestAppium {
AndroidDriver<MobileElement> driver;
#BeforeTest
public void setup() {
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability("platformName", "Android");
cap.setCapability("deviceName", "emulator-5554"); //used emulator, but should be set devices guid in Your case "xiaomi-2014818-204648717d62"
cap.setCapability("version", "5.1.1");
cap.setCapability("appActivity", "com com.mediamushroom.copymydata.app.EasyMigrateActivity");
cap.setCapability("appPackage", "com.mediamushroom.copymydata");
try {
driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
#Test
public void testAppiumSimulator() {
MobileElement element = driver.findElement(By.id("NextButton"));
element.click();
// do some Assertion
Assert.assertTrue(//some condition//);
}
#AfterTest
public void tearDown() {
driver.quit();
}
}
And this is an simple Appium test...
Hope this helps,

Selenium WebDriver throwing TimoutException while invoking getScreenshotAs()

This is my code.
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "data/chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(30, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "logs/ss/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
}
All time when driver.get() throw TimeoutException I want to take a screenshot at browser.
But when throw TimeoutException, getScreenshotAs() from printSS() don't take screenshot because throw another TimeoutException.
Why getScreenshotAs() throw TimeoutException and how to take screenshot at browser
P.S.: Increase pageLoadTimeout time is not the answer I want.
While working with Selenium 3.x, ChromeDriver 2.36 and Chrome 65.x you need to mention the relative path of the location (with respect of your project) where you intend to store the screenshot.
I took you code and did a few minor modification as follows :
Declared driver as WebDriver instance as static and added #Test annotation.
Reduced pageLoadTimeout to 2 seconds to purposefully raise the TimeoutException.
Changed the location of String path to a sub-directory wthin the project scope as follows :
String path = "./ScreenShots/";
Added a log as :
System.out.println("Screenshot Taken");
Here is the code block :
package captureScreenShot;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.TimeoutException;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.Test;
public class q49319748_captureScreenshot
{
public static WebDriver drive;
#Test
public static void test1() throws IOException {
System.setProperty("webdriver.chrome.driver", "C:\\Utility\\BrowserDrivers\\chromedriver.exe");
drive = new ChromeDriver();
drive.manage().timeouts().pageLoadTimeout(2, TimeUnit.SECONDS);
try {
drive.get("http://youtube.com");
}catch(TimeoutException e) {
printSS();
}
}
public static void printSS() throws IOException{
String path = "./ScreenShots/";
File scrFile = ((TakesScreenshot)drive).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File(path + "asdasdas" + ".jpg"));
System.out.println("Screenshot Taken");
}
}
Console Output :
[TestNG] Running:
C:\Users\username\AppData\Local\Temp\testng-eclipse--153679036\testng-customsuite.xml
Starting ChromeDriver 2.36.540470 (e522d04694c7ebea4ba8821272dbef4f9b818c91) on port 42798
Only local connections are allowed.
Mar 16, 2018 5:37:59 PM org.openqa.selenium.remote.ProtocolHandshake createSession
INFO: Detected dialect: OSS
Screenshot Taken
PASSED: test1
Screenshot :
Reference
You can find a detailed discussion in How to take screenshot with Selenium WebDriver
The problem is that while Selenium waits for the page to complete loading it cannot take any other command. This is why it throws TimeoutException also from the exception handler when you try take the screenshot.
The only option I see is to take the screenshot not through Selenium, but using other means that take a screenshot of the entire desktop. I've written such a thing in C#, but I'm pretty sure you can either find a way to do it in Java too.

Error in fire fox selenium web driver

Recently, bump into this issues with selenium firefox driver.
Thanks in advance
Set UP
os.name: 'Mac OS X',
os.arch: 'x86_64',
os.version: '10.12.6',
java.version: '1.8.0_131'
Firefox version 56.0.1 (64-bit)
Gecko Driver Latest 0.19.0
The error shows failed:
org.openqa.selenium.SessionNotCreatedException: Tried to run command
without establishing a connection
I tried different ways to tackle it but always come with the same error.
1. update all the selenium test driver to the latest
2. specify the directory export PATH = $PATH driverDir
My code
package automationFramework;
import org.apache.commons.io.FileUtils;
import org.junit.*;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.openqa.selenium.safari.SafariDriver;
import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import static org.junit.Assert.assertEquals;
public class GeckoDriver {
private static WebDriver driver;
public static int random = 0;
private String baseURL;
// #BeforeClass : Executes only once for the Test-Class.
#BeforeClass
public static void setting_SystemProperties(){
System.out.println("System Properties seting Key value.");
}
// #Before : To execute once before ever Test.
#Before
public void test_Setup(){
System.out.println("Launching Browser");
if (random == 0) {
System.out.println("Start Chrome Browser Testing ");
System.setProperty("webdriver.gecko.driver", "/Users/Fannity/Desktop/Drivers/geckodriver"); // Chrome Driver Location.
driver = new FirefoxDriver();
}
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
System.out.println("Session ID : " + ((RemoteWebDriver) driver).getSessionId() );
}
#Test
public void selenium_ScreenShot() throws IOException {
baseURL = "https://www.google.com/";
driver.get(baseURL);
System.out.println("Selenium Screen shot.");
File screenshotFile = ((RemoteWebDriver) driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(screenshotFile, new File("/Users/Fannity/Desktop/JUNIT-Selenium.jpg"));
random += 1;
}
// #After : To execute once after ever Test.
#After
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.close();
driver.quit();
}
// #AfterClass : Executes only once before Terminating the Test-Class.
#AfterClass
public static void clearing_SystemProperties(){
System.out.println("System Property Removing Key value.");
System.clearProperty("webdriver.gecko.driver");
}
}
ERROR
https://gist.github.com/Fenici/f82f885486de37ae110fda8d7430df6e
Your problem is here:
#After
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.close();
driver.quit();
}
Try only with close().
Explanation here.
We generally get this , if we use driver.close() and driver.quit() together so it would be better if you remove driver.close();
public void test_Cleaning(){
System.out.println("Closing Browser");
baseURL = null;
driver.quit();
}

Mvn Test cmd line Build Failure, Test Works in Eclipse

This is the circumstance. I am an QA Automation Engineer and right now I am being charged with setting up our CI framework in Jenkins but right now I am having issues with Maven. I am getting this error below when I try to run the mvn test command. However the tests work flawlessly in eclipse when run as maven test.
T E S T S
-------------------------------------------------------
Running TestSuite
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configur
ator#3830f1c0
Configuring TestNG with: org.apache.maven.surefire.testng.conf.TestNG652Configur
ator#bd8db5a
Tests run: 16, Failures: 1, Errors: 0, Skipped: 14, Time elapsed: 0.66 sec <<< F
AILURE!
beforeTest(fcstestingsuite.fsnrgn.LoginTest) Time elapsed: 0.442 sec <<< FAILU
RE!
java.lang.IllegalStateException: The path to the driver executable must be set b
y the webdriver.chrome.driver system property; for more information, see https:/
/github.com/SeleniumHQ/selenium/wiki/ChromeDriver. The latest version can be dow
nloaded from http://chromedriver.storage.googleapis.com/index.html
at com.google.common.base.Preconditions.checkState(Preconditions.java:19
9)
at org.openqa.selenium.remote.service.DriverService.findExecutable(Drive
rService.java:109)
at org.openqa.selenium.chrome.ChromeDriverService.access$000(ChromeDrive
rService.java:32)
at org.openqa.selenium.chrome.ChromeDriverService$Builder.findDefaultExe
cutable(ChromeDriverService.java:137)
at org.openqa.selenium.remote.service.DriverService$Builder.build(Driver
Service.java:296)
at org.openqa.selenium.chrome.ChromeDriverService.createDefaultService(C
hromeDriverService.java:88)
at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:116)
at fcstestingsuite.fsnrgn.LoginTest.beforeTest(LoginTest.java:54)
Results :
Failed tests: beforeTest(fcstestingsuite.fsnrgn.LoginTest): The path to the dr
iver executable must be set by the webdriver.chrome.driver system property; for
more information, see https://github.com/SeleniumHQ/selenium/wiki/ChromeDriver.
The latest version can be downloaded from http://chromedriver.storage.googleapis
.com/index.html
Tests run: 16, Failures: 1, Errors: 0, Skipped: 14
As you can see it is related to my chrome system property/path. In my project I have a test package and page object package. I set my chrome system property in the object class and import that class into the test class which works fine in eclipse. I'm not quite sure why Maven is having an issue with this. See sample object and test class below
Page Class
package pageobjectfactory;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
import org.testng.Assert;
// URL = http://www.ourfsn.com/myfsn/
public class Ourfsnlogin {
#FindBy(id="ctl00_ContentPlaceHolder1_tbxUname")
WebElement login;
#FindBy(id="ctl00_ContentPlaceHolder1_tbxPword")
WebElement password;
#FindBy(id="ctl00_ContentPlaceHolder1_btnSubmit")
WebElement submit;
#FindBy(name="ctl00$ContentPlaceHolder1$rptAccounts$ctl01$AccountSwitch")
WebElement PETSMARTUS;
#FindBy(name="ctl00$ContentPlaceHolder1$rptAccounts$ctl02$AccountSwitch")
WebElement PETSMARTCAD;
#FindBy(name="ctl00$ContentPlaceHolder1$rptAccounts$ctl03$AccountSwitch")
WebElement PETSMARTPR;
#FindBy(id="ctl00_lblTopLogin")
WebElement PETSMARTUSASSERT;
#FindBy(id="ctl00_lblTopLogin")
WebElement PETSMARTCAASSERT;
#FindBy(id="ctl00_lblTopLogin")
WebElement PETSMARTPRASSERT;
#FindBy(id="ctl00_Menu1_16")
WebElement LogoutButton;
public static WebDriver driver;
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\\Users\\dmohamed\\Documents\\Testing Environment\\Testing Environment\\Web Drivers\\chromedriver_win32 (1)\\chromedriver.exe");
WebDriver chromedriver = null; new ChromeDriver();
driver= chromedriver;
}
//Send user name in textbox
public void sendUserName(String strUsername){
login.sendKeys("ebluth");}
public void sendUserNameServiceCenter(String strUsername){
login.sendKeys("servicecenter");}
public void sendUserNameSP(String strUsername){
login.sendKeys("4328701");
}
//Send Password
public void sendPassword(String strPassword){
password.sendKeys("password");}
//submitting credentials
public void clicksubmit(){
submit.click();}
//Checking US PAge
public void USAssertion(){
PETSMARTUS.isEnabled();
}
//Checking CAD page
public void CAAssertion(){
PETSMARTCAD.isEnabled();}
//Checking PR Page
public void PRAssertion(){
PETSMARTPR.isEnabled();}
//click us link
//Checking US PAge
public void USclick(){
PETSMARTUS.click();
}
//Checking CAD page
public void CAclick(){
PETSMARTCAD.click();}
//Checking PR Page
public void PRclick(){
PETSMARTPR.click();}
//Click on
public void USPageValidation(){
Assert.assertTrue(PETSMARTUSASSERT.getText().contains("PETM-US"), "Incorrect Page [US,CA,PR]");
}
public void PRPageValidation(){
Assert.assertTrue(PETSMARTPRASSERT.getText().contains("PETM-PR"),"Incorrect Page [US,CA,PR]");
}
public void CAPageValidation(){
Assert.assertTrue(PETSMARTCAASSERT.getText().contains("PETM-CN"),"Incorrect Page [US,CA,PR]");
}
//Log out
public void Logout (){
LogoutButton.click();
}}
Test Class
package fcstestingsuite.fsnrgn;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import pageobjectfactory.Ourfsnlogin;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.pagefactory.AjaxElementLocatorFactory;
public class LoginTest {
static WebDriver driver;
Ourfsnlogin LoginPage;
#Test (priority=1)
public void USPageTest() {
LoginPage.sendUserName("ebluth");
LoginPage.sendPassword("password");
LoginPage.clicksubmit();
LoginPage.USclick();
LoginPage.USPageValidation();
}
#Test(priority=2)
public void CAPageTest(){
LoginPage.sendUserName("ebluth");
LoginPage.sendPassword("password");
LoginPage.clicksubmit();
LoginPage.CAclick();
LoginPage.CAPageValidation();
}
#Test (priority=3)
public void PRPageTest(){
LoginPage.sendUserName("ebluth");
LoginPage.sendPassword("password");
LoginPage.clicksubmit();
LoginPage.PRclick();
LoginPage.PRPageValidation();
}
#AfterMethod
public void aftermethod(){
LoginPage.Logout();
}
#BeforeTest
public void beforeTest() {
Ourfsnlogin.driver=new ChromeDriver();
//setting global explicit wait
PageFactory.initElements(new AjaxElementLocatorFactory(driver, 20), this);
Ourfsnlogin.driver.get("http://www.ourfsn.com/myfsn");
//initiating elements in page factory
LoginPage= PageFactory.initElements(Ourfsnlogin.driver, Ourfsnlogin.class);
}
#AfterTest
public void afterTest() {
Ourfsnlogin.driver.quit();
}
}
The structure of your tests seems incorrect. You have a main method in the LoginPage - which is doing driver instantiation. Where is the main method being called from? Your beforetest also has a driver instantiation code which is called by testng but there you are not setting the chromedriver property.
Ideally the driver instantiation code should be written at one place and be consumed from the rest of the testcases.

Categories

Resources