Selenium pageFactory NullPointerException for driver - selenium

Selenium pageFactory NullPointerException. Any help will be appreciated. It works for the login of setUp(), but after that driver comes up null.
public class TestBase {
public WebDriver driver;
String url = PropertiesFile.readPropertiesFile("autUrl");
public WebDriver getDriver() {
System.setProperty("webdriver.chrome.driver",
System.getProperty("user.dir") + "/driver/chromedriver.exe");
driver = new ChromeDriver();
return driver;
}
public void getUrl(String url) {
driver.get(url);
driver.manage().window().maximize();
}
public void init() {
getDriver();
getUrl(url);
}
}
public class LogInPage extends TestBase {
WebDriver driver;
#FindBy(id = "loginEmail")public WebElement userName_field;
#FindBy(name = "password")public WebElement password_field;
#FindBy(xpath = "//*[#id='main-content']/aside/div/form/input[2]")public WebElement SignMeIn_btn;
public LogInPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
// Login
public void logIn(String userName, String password) {
userName_field.sendKeys(userName);
password_field.sendKeys(password);
SignMeIn_btn.click();
}
}
public class LogIn extends TestBase {
LogInPage logInPage;
private String user = PropertiesFile.readPropertiesFile("user");
private String password = PropertiesFile.readPropertiesFile("password");
public LogIn(WebDriver driver) {
this.driver = driver;
}
public void setUp(){
init();
}
public void logIn(){
logInPage = new LogInPage(driver);
logInPage.logIn(user, password);
}
}
public class PortalsPage extends TestBase {
WebDriver driver;
#FindBy(id = "loginEmail") public WebElement userName_field;
#FindBy(xpath=".//*[#id='tabDetail']") public WebElement tenantPage_li;
#FindBy(id="tabDetail") public WebElement ownerPage_li;
#FindBy(xpath="//a[contains(#href,'tenant.action')]") public WebElement tenantPortal_link;
#FindBy(xpath="//a[contains(#href,'owner.action')]") public WebElement ownerPortal_link;
public PortalsPage(WebDriver driver){
this.driver = driver;
PageFactory.initElements(driver, this);
}
public void goToPortals(){
userName_field.sendKeys("a");
tenantPage_li.click();
}
}
public class Portals extends TestBase {
PortalsPage portals;
WebDriver driver;
#BeforeClass
public void setUp(){
LogIn login = new LogIn(driver);
login.setUp();
login.logIn();
}
#Test
public void goToPortal(){
portals = new PortalsPage(driver);
portals.goToPortals();
}
}
Following exception I got:
FAILED: goToPortal 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.$Proxy6.sendKeys(Unknown Source) at
com.demo.pages.PortalsPage.goToPortals(PortalsPage.java:30) at
com.demo.control.Portals.goToPortal(Portals.java:28) 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:80)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:714) at
org.testng.internal.Invoker.invokeTestMethod(Invoker.java:901) at
org.testng.internal.Invoker.invokeTestMethods(Invoker.java:1231) at
org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:127)
at
org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:767) at
org.testng.TestRunner.run(TestRunner.java:617) at
org.testng.SuiteRunner.runTest(SuiteRunner.java:334) at
org.testng.SuiteRunner.runSequentially(SuiteRunner.java:329) at
org.testng.SuiteRunner.privateRun(SuiteRunner.java:291) at
org.testng.SuiteRunner.run(SuiteRunner.java:240) at
org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52) at
org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86) at
org.testng.TestNG.runSuitesSequentially(TestNG.java:1198) at
org.testng.TestNG.runSuitesLocally(TestNG.java:1123) at
org.testng.TestNG.run(TestNG.java:1031) at
org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)

Your current approach seems to be a bit convoluted. But without delving into the details of what other approach you can use to fix your overall design, here's a cleaned up version of your code, that should work.
The idea here is that you only need page classes (the ones that end with *Page which represent a particular page, and exposes some business functions that can be executed on that particular page) and test classes, with the test class themselves extending from your TestBase
So here are the classes
LoginPage.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class LogInPage {
#FindBy(id = "loginEmail")
private WebElement userNameTextField;
#FindBy(name = "password")
private WebElement passwordTextField;
#FindBy(xpath = "//*[#id='main-content']/aside/div/form/input[2]")
private WebElement signInButton;
public LogInPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void logIn(String userName, String password) {
userNameTextField.sendKeys(userName);
passwordTextField.sendKeys(password);
signInButton.click();
}
}
PortalsPage.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class PortalsPage {
#FindBy(id = "loginEmail")
private WebElement usernameTextField;
#FindBy(xpath = ".//*[#id='tabDetail']")
private WebElement tenantPage;
#FindBy(id = "tabDetail")
private WebElement ownerPage;
#FindBy(xpath = "//a[contains(#href,'tenant.action')]")
private WebElement tenantPortalLink;
#FindBy(xpath = "//a[contains(#href,'owner.action')]")
private WebElement ownerPortalLink;
public PortalsPage(WebDriver driver) {
PageFactory.initElements(driver, this);
}
public void goToPortals() {
usernameTextField.sendKeys("a");
tenantPage.click();
}
}
TestBase.java
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class TestBase {
private WebDriver driver;
protected WebDriver getDriver() {
if (driver != null) {
return driver;
}
System.setProperty("webdriver.chrome.driver", System.getProperty("user.dir") + "/driver/chromedriver.exe");
driver = new ChromeDriver();
return driver;
}
public void getUrl(String url) {
getDriver().get(url);
getDriver().manage().window().maximize();
}
}
PortalsTest.java
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class PortalsTest extends TestBase {
private PortalsPage portals;
private String user = PropertiesFile.readPropertiesFile("user");
private String password = PropertiesFile.readPropertiesFile("password");
private String url = PropertiesFile.readPropertiesFile("autUrl");
#BeforeClass
public void setUp() {
LogInPage login = new LogInPage(getDriver());
getUrl(url);
login.logIn(user, password);
}
#Test
public void goToPortal() {
portals = new PortalsPage(getDriver());
portals.goToPortals();
}
}

Related

How to run tests in parallel by classes with TestNG and Selenium with POM Pattern

I am using webdrivermanager with driver call.
But it retains the pom pattern and is difficult to construct in parallel using the threadlocal class.
My module is structured as below.
Some of my code.
Driver class
public class Driver {
public WebDriver setDriver(WebDriver driver, String browser, String lang) throws Exception {
if (browser.contains("Chrome")) {
ChromeOptions options = new ChromeOptions();
WebDriverManager.chromedriver().clearResolutionCache().clearDriverCache().setup();
}
options.addArguments(lang);
driver = new ChromeDriver(options);
Capabilities cap = ((RemoteWebDriver) driver).getCapabilities();
} else {
WebDriverManager.iedriver().clearResolutionCache().clearDriverCache().setup();
}
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
return driver;
}
}
Next Pageclass
public class LoginPage{
private WebDriver driver;
#CacheLookup
#FindBy(id = "j_domain")
public static WebElement domainField;
#CacheLookup
#FindBy(id = "j_username")
public static WebElement usernameField;
#CacheLookup
#FindBy(id = "j_password")
public static WebElement passwordField;
public LoginPage(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver,this);
}
}
Next Base testclass :
public class BaseTest {
public WebDriver driver;
public LoginPage loginPage;
#Parameters({"browser"})
#BeforeClass
public void Setup(ITestContext context, String browsertype) throws Exception {
pageFactory.driver.Driver driversetting = new pageFactory.driver.Driver();
driver = driversetting.setDriver(driver, browsertype, "lang=ko_KR");
context.setAttribute("webDriver", driver);
loginPage = new LoginPage(driver);
}
}
Next testclass
public class Remotepc_Center extends BaseTest {
#Test(priority = 1, enabled = true)
public void a1(Method method) throws Exception {
}
}
Using threadlocal I want sessions to be configured independently and tests running in parallel.
You would need to follow the below sugggestions/recommendations in order for you to be able to work with Page Object Model and thread local variables, please do the following:
Make use of a library such as autospawn to handle the webdriver instances backed by thread local variables.
Make sure that you create Page Objects only within your test methods because that's the only place wherein your thread local variables would have a webdriver that can be accessed by the test method as well. Querying the thread local variable for retrieving the webdriver instance from within a configuration method such as #BeforeClass (in the testng world) is going to give you a different thread.
In TestNG context, only a #BeforeMethod, #Test and a #AfterMethod are guaranteed to run in the same thread.
For additional details on how to work with a thread local variable, you can perhaps refer to my blog
For the sake of completeness, including relevant code snippets for the thread local creation.
Define a factory that can create webdriver instances as below
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
class LocalDriverFactory {
static WebDriver createInstance(String browserName) {
WebDriver driver = null;
if (browserName.toLowerCase().contains("firefox")) {
driver = new FirefoxDriver();
return driver;
}
if (browserName.toLowerCase().contains("internet")) {
driver = new InternetExplorerDriver();
return driver;
}
if (browserName.toLowerCase().contains("chrome")) {
driver = new ChromeDriver();
return driver;
}
return driver;
}
}
Define a driver manager class that looks like below:
import org.openqa.selenium.WebDriver;
public class LocalDriverManager {
private static ThreadLocal<WebDriver> webDriver = new ThreadLocal<WebDriver>();
public static WebDriver getDriver() {
return webDriver.get();
}
static void setWebDriver(WebDriver driver) {
webDriver.set(driver);
}
}
Define a TestNG listener that looks like below
import org.openqa.selenium.WebDriver;
import org.testng.IInvokedMethod;
import org.testng.IInvokedMethodListener;
import org.testng.ITestResult;
public class WebDriverListener implements IInvokedMethodListener {
#Override
public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
String browserName = method.getTestMethod().getXmlTest().getLocalParameters().get("browserName");
WebDriver driver = LocalDriverFactory.createInstance(browserName);
LocalDriverManager.setWebDriver(driver);
}
}
#Override
public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
if (method.isTestMethod()) {
WebDriver driver = LocalDriverManager.getDriver();
if (driver != null) {
driver.quit();
}
}
}
}
A typical test case would now look like below:
import org.testng.annotations.Test;
public class ThreadLocalDemo {
#Test
public void testMethod1() {
invokeBrowser("http://www.ndtv.com");
}
#Test
public void testMethod2() {
invokeBrowser("http://www.facebook.com");
}
private void invokeBrowser(String url) {
System.out.println("Thread " + Thread.currentThread().getId());
System.out.println("HashcodeebDriver instance = " +
LocalDriverManager.getDriver().hashCode());
LocalDriverManager.getDriver().get(url);
}
}

In Page Object Model do i have to create webdriver all the time?

I'm using the Page Object Model I just started i created 2 packages one is com.automation.pages another one is com.automation.testcases.
In both packages I created a class for the login page it works fine I'm sharing the code below.
package com.automation.pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
public class LoginPage {
WebDriver driver;
public LoginPage(WebDriver ldriver)
{
this.driver=ldriver;
}
#FindBy (xpath="//input[#name='email'] ") WebElement email;
#FindBy (xpath="//input[#name='password']") WebElement password;
#FindBy (xpath="//body/div[2]/div[2]/div[2]/form[1]/div[3]/div[2]/button[1]") WebElement loginbutton;
public void logintoLabaiik(String email1, String password1 )
{
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
email.sendKeys(email1);
password.sendKeys(password1);
loginbutton.click();
}
}
The problem I'm facing when I working on the new page is when I created a driver and when using ldriver it throws me an error also when I replace the "l" still it throws me the error. kindly solve my problem.
package com.automation.pages;
import org.openqa.selenium.WebDriver;
public class TaxSetup {
WebDriver driver;
public TaxSetup(WebDriver driver)
{
this.driver.ldriver;
}
}
It looks you have an issue in TaxSetup constructor.
This should work.
public TaxSetup(WebDriver driver){
this.driver=driver;
}
Take a look at how to create 2 Page Object classes and use them in tests:
LoginPage
public class LoginPage {
final WebDriver driver;
public LoginPage(WebDriver driver){
this.driver=driver;
}
// page implementation
}
TaxSetup
public class TaxSetup {
final WebDriver driver;
public TaxSetup(WebDriver driver){
this.driver=driver;
}
// page implementation
}
How to use in test
public class SomeTest {
WebDriver driver;
LoginPage loginPage;
TaxSetup taxSetupPage;
#BeforeClass
public void initDriverAndPages() {
driver = ... // e.g. new ChromeDriver()
loginPage = PageFactory.initElements(driver, LoginPage.class);
taxSetupPage = PageFactory.initElements(driver, TaxSetup.class);
}
#Test
public void someTest() {
// implement test using loginPage, taxSetupPage as you like
}
#AfterClass
public void quitDriver() {
driver.quit();
}
}
Please correct the below line in your TaxSetUp constructor.
this.driver.ldriver;
This is suppose to be
this.driver = driver;
And yes, you have to pass the WebDriver instance for all the page classes that you create as part of your application otherwise they will assign default value to the driver which is null.

Getting java.lang.NullPointerException in Selenium WebDriver

I am getting java.lang.NullPointerException when I run the testcase in Eclipse. Can somebody help me in pointing out the error I have made.
Error # Line 17: WebElement in LoginPage.Java.
# Line 12: LoginPage in TC_LoginTest_001.java.
**LoginPage.Java**
package com.internetBanking.pageObjects;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
public class LoginPage {
WebDriver driver;
public LoginPage (WebDriver driver) {
this.driver = driver;
}
WebElement usrname = driver.findElement(By.name("uid"));
WebElement pwd = driver.findElement(By.name("password"));
WebElement login = driver.findElement(By.name("btnLogin"));
public void setUsrname(String uname) {
usrname.sendKeys(uname);
}
public void setPwd(String pswd) {
pwd.sendKeys(pswd);
}
public void login() {
login.click();
}
}
**TC_LoginTest_001.java**
package com.internetBanking.testCases;
import org.testng.annotations.Test;
import com.internetBanking.pageObjects.LoginPage;
public class TC_LoginTest_001 extends BaseClass {
#Test
public void LoginTest() {
driver.get(baseURL);
logger.info("URL is opened");
LoginPage loginPage = new LoginPage(driver);
loginPage.setUsrname(username);
logger.info("Username is entered");
loginPage.setPwd(password);
logger.info("Password is entered");
loginPage.login();
logger.info("Login button is clicked");
}
}
When I run the test case, I am getting the below errors:
java.lang.NullPointerException
at com.internetBanking.pageObjects.LoginPage.(LoginPage.java:17)
at com.internetBanking.testCases.TC_LoginTest_001.LoginTest(TC_LoginTest_001.java:12)
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:124)
at org.testng.internal.Invoker.invokeMethod(Invoker.java:583)
at org.testng.internal.Invoker.invokeTestMethod(Invoker.java:719)
at org.testng.internal.Invoker.invokeTestMethods(Invoker.java:989)
at org.testng.internal.TestMethodWorker.invokeTestMethods(TestMethodWorker.java:125)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:109)
at org.testng.TestRunner.privateRun(TestRunner.java:648)
at org.testng.TestRunner.run(TestRunner.java:505)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:455)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:450)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:415)
at org.testng.SuiteRunner.run(SuiteRunner.java:364)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:84)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1208)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1137)
at org.testng.TestNG.runSuites(TestNG.java:1049)
at org.testng.TestNG.run(TestNG.java:1017)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:115)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:251)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:77)
Consider this code:
public class MainTest {
public static void main(String[] args) {
new Test(new Object());
}
}
class Test {
InitMe initMe = new InitMe();
public Test(Object o){
System.out.println("Test instance has been created");
}
}
class InitMe{
public InitMe(){
System.out.println("Init me instance has been created");
}
}
If you run it you will see the following output:
Init me instance has been created
Test instance has been created
which means that fields are initialized before the constructor is executed. So in your case you have the following structure:
public class MainTest {
public static void main(String[] args) {
new Test(new Object());
}
}
class Test {
Object o;
String oStr = o.toString();
public Test(Object o){
this.o = o;
}
}
where your fields are initialized through the reference that has not been yet initialized itself (because the constructor has not yet been called).
Your particular solution would be to change this:
WebDriver driver;
public LoginPage (WebDriver driver) {
this.driver = driver;
}
WebElement usrname = driver.findElement(By.name("uid"));
WebElement pwd = driver.findElement(By.name("password"));
WebElement login = driver.findElement(By.name("btnLogin"));
to this:
WebDriver driver;
WebElement usrname;
WebElement pwd;
WebElement login;
public LoginPage (WebDriver driver) {
this.driver = driver;
usrname = driver.findElement(By.name("uid"));
pwd = driver.findElement(By.name("password"));
login = driver.findElement(By.name("btnLogin"));}
}

Null Pointer Exception in Selenium WebDriver in second page after successful login Page

How to resolve below exception.
Here is code
package com;`
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Browserfactory {
static WebDriver driver;
public static WebDriver startBrowser(String browserName)
{
if(browserName.equalsIgnoreCase("firefox"))
{
System.setProperty("webdriver.firefox.marionette","geckodriver.exe");
driver = new FirefoxDriver();
}
else if(browserName.equalsIgnoreCase("chrome"))
{
System.setProperty("webdriver.chrome.driver","chromedriver.exe");
driver = new ChromeDriver();
}
return driver;
}
}
Accessing from another class.
below code is written in different class and accessing this as a Base class.
i wanted to make Logout method as utility, when ever required to logout just call it and get done.
package com;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
public class Guru99 {
//creating a guru99 bank page login verify.
public WebDriver driver=null;
private static final String URL="http://demo.guru99.com/v4/";
#BeforeTest
//pre-requisition
public void launchpage()
{
WebDriver driver = Browserfactory.startBrowser("firefox");
driver.get(URL);
driver.findElement(By.name("uid")).sendKeys("mngr117051");
driver.findElement(By.name("password")).sendKeys("EhYtErY");
driver.findElement(By.name("btnLogin")).click();
}
#Test
public void logout()
{
driver.findElement(By.xpath("html/body/div[2]/div/ul/li[15]/a")).click();
}
}
//Running code through TestNG.
Getting Error
FAILED: logout
java.lang.NullPointerException
at com.Guru99.logout(Guru99.java:26)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
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:1137)
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:753)
at org.testng.TestRunner.run(TestRunner.java:607)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:368)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:363)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:321)
at org.testng.SuiteRunner.run(SuiteRunner.java:270)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1284)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1209)
at org.testng.TestNG.runSuites(TestNG.java:1124)
at org.testng.TestNG.run(TestNG.java:1096)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:236)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:81)
That is because of the mistake you have done in your code.
I didn't understand why you have declared driver in 3 places in your code. Whenever you declare same variable again and again its previous value get override every time and that is the reason you are getting NullPointerException.
I have modified your code and verified the working also.
public class Browserfactory {
public static WebDriver startBrowser(WebDriver driver,String browserName) {
if (browserName.equalsIgnoreCase("firefox")) {
System.setProperty("webdriver.firefox.marionette","geckodriver.exe");
driver = new FirefoxDriver();
} else if (browserName.equalsIgnoreCase("chrome")){
System.setProperty("webdriver.chrome.driver", "chromedriver.exe");
driver = new ChromeDriver();
}
return driver;
}
}
public class Guru99 {
// creating a guru99 bank page login verify.
public WebDriver driver = null;
private static final String URL = "https://demo.guru99.com/v4";
#BeforeTest
// pre-requisition
public void launchpage() {
driver = Browserfactory.startBrowser(driver,"firefox");
driver.manage().window().maximize();
driver.get(URL);
driver.findElement(By.name("uid")).sendKeys("mngr117051");
driver.findElement(By.name("password")).sendKeys("EhYtErY");
driver.findElement(By.name("btnLogin")).click();
}
#Test
public void logout() {
driver.findElement(By.xpath("html/body/div[2]/div/ul/li[15]/a")).click();
}
}
Hope this will help you.

Page Object Pattern with Selenium and Testng failure

I am having issue running the below Page Object Model with testng.
TestClass 1
package Proj;
public class signInPage {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "C:/chromedriver_win32/chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
public signInPage (WebDriver driver)
{
this.driver=driver;
}
WebDriver driver;
public signInPage()
{
driver.get("baseURL");
}
By Email_address = By.name("Username");
By Password = By.id("Password");
public WebElement Email_address ()
{
return driver.findElement(Email_address);
}
public WebElement Password ()
{
return driver.findElement(Password);
}
public WebElement button_id ()
{
return driver.findElement(button_id);
}
}
TestClass 2
package Proj;
public class MyDetailsPage {
public MyDetailsPage (WebDriver driver)
{
this.driver=driver;
}
WebDriver driver;
By My_Details=By.xpath(".//*[#id='masterForm']/div[5]/div/div[3]/div[3]/a/span");
By First_name = By.id("FirstName");
By Last_name= By.name("NameModel.LastName");
By button_id= By.id("stage_one_button");
public WebElement My_Details ()
{
return driver.findElement(My_Details);
}
public WebElement First_name ()
{
return driver.findElement(First_name);
}
public WebElement Last_name ()
{
return driver.findElement(Last_name);
}
}
TestData Page
package Proj;
public class testData {
public static void main (String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:/chromedriver_win32/chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
}
public void testDetails (WebDriver driver)
{
this.driver=driver;
}
static WebDriver driver;
protected static String baseUrl;
protected static String Email_address;
protected static String Password;
protected String First_name;
protected String Last_name;
public void Data () {
baseUrl = "https://login.yahoo.com/";
driver = new ChromeDriver();
Email_address = "myname#yahoo.com";
Password = "myname";
First_name = "Testing";
Last_name = "Account";
}
}
TestCases
package Proj;
import org.testng.annotations.Test;
import org.openqa.selenium.SearchContext;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeSuite;
public class TestCases extends testData {
private static SearchContext WebElement;
#BeforeSuite
public void BeforeSuite () {
System.setProperty("webdriver.chrome.driver", "C:/chromedriver_win32/chromedriver.exe");
WebDriver driver = new ChromeDriver ();
}
#BeforeClass
public void driver(WebDriver driver) throws InterruptedException
{
this.driver = driver;
driver.get(baseUrl);
}
#Test
public void AllTest () throws InterruptedException {
signInPage a = new signInPage (driver);
a.Email_address().sendKeys(Email_address);
a.Password().sendKeys(Password);
a.SIGN_IN().click();
MyDetailsPage e = new MyDetailsPage (driver);
e.My_Details ().click();
e.First_name ().sendKeys("Testing");
e.Last_name (). sendKeys ("Account");
e.button_id ().click();
}
}
It opens up Browser but fail to enter baseUrl and could not perform the Test. It is failing from the TestCases class. No matter how i have tried to reconfigure this with no luck. I appreciate your prompt assistance. Thank you
FAILED CONFIGURATION: #BeforeClass driver
org.testng.TestNGException:
Can inject only one of <ITestContext, XmlTest> into a BeforeClass annotated driver.
For more information on native dependency injection please refer to http://testng.org/doc/documentation-main.html#native-dependency-injection
at org.testng.internal.Parameters.checkParameterTypes(Parameters.java:244)
at org.testng.internal.Parameters.createParameters(Parameters.java:172)
at org.testng.internal.Parameters.createParameters(Parameters.java:458)
at org.testng.internal.Parameters.createConfigurationParameters(Parameters.java:118)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:206)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:146)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:166)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
SKIPPED: AllTest
org.testng.TestNGException:
Can inject only one of <ITestContext, XmlTest> into a BeforeClass annotated driver.
For more information on native dependency injection please refer to http://testng.org/doc/documentation-main.html#native-dependency-injection
at org.testng.internal.Parameters.checkParameterTypes(Parameters.java:244)
at org.testng.internal.Parameters.createParameters(Parameters.java:172)
at org.testng.internal.Parameters.createParameters(Parameters.java:458)
at org.testng.internal.Parameters.createConfigurationParameters(Parameters.java:118)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:206)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:146)
at org.testng.internal.TestMethodWorker.invokeBeforeClassMethods(TestMethodWorker.java:166)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:105)
at org.testng.TestRunner.privateRun(TestRunner.java:744)
at org.testng.TestRunner.run(TestRunner.java:602)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:380)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:375)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:340)
at org.testng.SuiteRunner.run(SuiteRunner.java:289)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1301)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1226)
at org.testng.TestNG.runSuites(TestNG.java:1144)
at org.testng.TestNG.run(TestNG.java:1115)
at org.testng.remote.AbstractRemoteTestNG.run(AbstractRemoteTestNG.java:132)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:230)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:76)
===============================================
Default test
Tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 0
===============================================
===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 0
===============================================
public void driver(WebDriver driver) is not allowed on a #BeforeClass method. You have to remove the parameter and find another way to set the driver.
As juherr pointed out that you can not parameterize the #BeforeClass in this manner by passing webdriver instead you can follow following approach to do so:
public class TestCases extends testData {
private static SearchContext WebElement;
WebDriver driver;
#BeforeSuite
public void BeforeSuite () throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\Eclipse\\Selenium\\chromedriver.exe");
}
#BeforeClass
public void driver() throws InterruptedException
{
driver = new ChromeDriver ();
testData td = new testData ();
driver.get(td.baseUrl);
}
/
/
/
/