java.lang.NullPointerException error On Page Object Model - java

Hi Guys I am following Page Object Model in Java with Cucumber.
I have following classes:
AbstractClass.java: Initiates the webdriver instance and serves as Master class for other object classes.
package ObjectRepository;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
/**
* Hello world!
*
*/
public class AbstractClass {
public static WebDriver driver=null;
Properties p = new Properties(); // create an object of properties
public AbstractClass(WebDriver driver){
this.driver=driver;
}
public void setup() throws IOException{
// file input stream obect
FileInputStream fi= new FileInputStream("C:\\Users\\sulemanmazhar\\Google Drive\\Automation Learning\\Java\\udemyWorkspace\\DebitCard_PageObject\\src\\test\\java\\Banking\\global.properties");
p.load(fi); // load the properties
if (p.getProperty("browser").contains("fireFox")){ // if browser in property file is firefox
driver=new FirefoxDriver();
};
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
}
public loginPage navigateToWelcomePage(){
String url=p.getProperty("url");
System.out.println(url);
driver.navigate().to(url);
return new loginPage(driver);
}
public String getTitle(){
String title= driver.getTitle().trim();
return title;
}
public void quitDriver(){
driver.quit();
}
}
loginPage.Java: Serves as Object repository class for login Page of my SUT. Inherits Abstract Class
package ObjectRepository;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
/**
* This class is within the object repository package
* This package will contain all the objects which will
* These objects will be stored and the will be accessed from the test/java folder
public class loginPage extends AbstractClass
public loginPage(WebDriver driver){
super(driver);
}
// all login page objects belong to this page
By username = By.name("userName"); // object
By password = By.name("password");
By name= By.name("login");
By registerLink = By.linkText("REGISTER");
By signInLink=By.linkText("SIGN-ON");
// constructor passes a webdriver object
public flightFinder login(String userId,String passw){
driver.findElement(username).sendKeys(userId);
driver.findElement(password).sendKeys(passw);
driver.findElement(name).click();
return new flightFinder(driver);
}
public registerPage navigateToRegister() {
driver.findElement(registerLink).click();
return new registerPage(driver);
}
public loginPage navigateToSignOn(){
driver.findElement(signInLink).click();
return new loginPage(driver);
}
}
I also have registerPage.java,flighFinder.java which serves the same purpose as loginPage.java
I have corresponding test classes for each of the classes. The two classes I want to discuss are:
stepsDefiniton.java : This class contains most of the common methods that are applicable across different classes.
package TestClasses;
import java.io.IOException;
import org.openqa.selenium.WebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import ObjectRepository.flightFinder;
import ObjectRepository.loginPage;
import ObjectRepository.registerPage;
import cucumber.api.java.After;
import cucumber.api.java.Before;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class StepsDefinition {
WebDriver driver;
loginPage loginPage;
//flightFinder flightFinder;
registerPage registerPage;
#Before
public void setUp() throws IOException{
System.out.println("Executing before method");
loginPage = new loginPage(driver);
loginPage.setup();
loginPage.navigateToWelcomePage();
}
#After
public void CloseDriver(){
System.out.println("Executing after method");
loginPage.quitDriver();
}
/* Shared steps */
#Given("^I am on \"([^\"]*)\" page$")
public void i_am_on_page(String page) {
if(page.equalsIgnoreCase("sign-on")){
loginPage=loginPage.navigateToSignOn();
}
if(page.equalsIgnoreCase("register")){
registerPage=loginPage.navigateToRegister();
}
String Title =loginPage.getTitle();
System.out.println("Actual page title is :"+ Title+" Expected Title is :"+page);
Assert.assertTrue(Title.contains(page));
}
#When("^I click on \"([^\"]*)\" button$")
public void i_click_on_button(String button) {
if (button.equalsIgnoreCase("register")){
registerPage=loginPage.navigateToRegister();
}
else if(button.equalsIgnoreCase("sign-on")){
loginPage=loginPage.navigateToSignOn();
}
}
#Then("^I should be navigated to \"([^\"]*)\" page$")
public void i_should_be_navigated_to_page(String page) {
String Title =loginPage.getTitle().trim();
System.out.println("Actual page is :"+Title +" Expected page is :"+page);
Assert.assertTrue(Title.contains(page));
}
}
LoginTest.Java : Is the Test class contains the code to test the logiN Page.
package TestClasses;
import org.openqa.selenium.WebDriver;
import ObjectRepository.flightFinder;
import ObjectRepository.loginPage;
import ObjectRepository.registerPage;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.When;
public class LoginTest {
//WebDriver driver;
loginPage loginPage;
flightFinder flightFinder;
registerPage registerPage;
/* Login Page */
#When("^I input my details as \"([^\"]*)\" and \"([^\"]*)\"$")
public void i_input(String username, String password) {
flightFinder=loginPage.login(username,password);
}
#Given("^I am logged in as \"([^\"]*)\" and \"([^\"]*)\"$")
public void i_am_logged_in(String username, String password){
flightFinder=loginPage.login(username,password);
}
}
Ok my question is:
When I execute the test all the tests within the StepsDefinition.java runs fine and as expectedly. As soon as it moves onto LoginTest.Java I get following error:
5 Scenarios ([31m3 failed[0m, [32m2 passed[0m)
16 Steps ([31m3 failed[0m, [36m5 skipped[0m, [32m8 passed[0m)
1m30.444s
java.lang.NullPointerException
at TestClasses.LoginTest.i_am_logged_in(LoginTest.java:30)
at ✽.Given I am logged in as "test" and "test"(featureFiles/flightFinder.feature:5)
java.lang.NullPointerException
at TestClasses.LoginTest.i_input(LoginTest.java:23)
at ✽.When I input my details as "test" and "test"(featureFiles/login.feature:12)
java.lang.NullPointerException
at TestClasses.Register_Test.i_input_my_details(Register_Test.java:21)
at ✽.When I input my details(featureFiles/register.feature:12)
What I think happening is, I am initiating the objects in stepsDefinition.Java class and as soon as the test moves onto another test class it is not carrying on with the previous state of the object.
If thats the case how can I pass on the state of one object to another? If not then where am I going wrong? Any help will be much appreciated.

The WebDriver is instantiated in the abstract class.
In the loginPage.Java,registerPage.java,flighFinder.java you are using driver which is not instantiated or driver which is instantiated in the abstract class is not passed to these classes.
Solution can be Remove driver=new FirefoxDriver(); from the setup of Abstract class instead place that in LoginTest and pass the driver object during loginPage,registerPage object creation.
ex: WebDriver driver = new ChromeDriver();
loginPage loginpage = new loginPage(driver);
I have tried it worked.

Related

NoSuchElementException in Selenium when testing login using Java

I am working on a Selenium testing framework tutorial of John Sonmez and ran into problem trying to perform the very first test. The test part consists of two methods: 1. LoginPage.GoTo(); which opens wordpress login page and 2. LoginPage.LoginAs("admin").Login(); which inserts username and clicks continue.
What happens when I run the test is wordpress loginpage opens and after 2 seconds blank Chrome browser opens and JUnit displays NoSuchElementException. The author of tutorial solved this problem adding some WebDriverWait and switchTo.ActiveElement.getAttribute() to LoginPage.GoTo(); method. However he is coding in C# and offers no solution for Java I'm coding in. I tried to apply WebDriverWait also but the problem is still there. Can anyone please suggest me how to solve this problem using WebDriverWait in Java.
LoginTest
import static org.junit.Assert.*;
import org.junit.Assert;
import org.junit.Test;
import wordpressAutomation.Driver;
import wordpressAutomation.LoginPage;
public class LoginTest extends Driver {
#Test
public void admin_user_can_login() {
LoginPage l = new LoginPage();
l.GoTo();
LoginPage.LoginAs("scenicrail").Login();
//Assert.assertTrue(DashboardPage.IsAt, "Failed to login");
}
}
LoginPage
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginPage extends Driver {
#Test
public void GoTo() {
openBrowser().get("https://wordpress.com/log-in");
}
public static LoginCommand LoginAs(String username) {
return new LoginCommand(username);
}
}
public class LoginCommand extends Driver {
private String username;
private String password;
public LoginCommand(String username) {
this.username = username;
}
public LoginCommand WithPassword(String password) {
this.password = password;
return this;
}
public void Login() {
WebElement login = openBrowser().findElement(By.xpath("//*[#id='usernameOrEmail']"));
login.sendKeys(username);
openBrowser().findElement(By.xpath("//button[#type = 'submit']")).click();
}
}
public class Driver {
public WebDriver openBrowser() {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\KatarinaOleg\\Desktop\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
After opening the page, where you get the NoSuchElementException you can add in something like this.
FluentWait<WebDriver> webDriverWait = new WebDriverWait(driver, 25).pollingEvery(5, TimeUnit.SECONDS);
webDriverWait.until(ExpectedConditions.visibilityOf(webElement));
Just add in whatever element you want to use as your check to make sure the page has loaded
you have called the Openbrowser multiple times in Login Method from LoginCommand Class.So, It will be unnecessarily create different driver instance. So, your code needs to be modified as below along with explicit wait (Driver Class also needs to be changed as below)
Login Method from LoginCommand Class:
public void Login() {
WebDriverWait wait=new WebDriverWait(driver,20);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='usernameOrEmail']")));
WebElement login = driver.findElement(By.xpath("//*[#id='usernameOrEmail']"));
login.sendKeys(username);
driver.findElement(By.xpath("//button[#type = 'submit']")).click();
}
Driver Class:
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Driver {
WebDriver driver;
public WebDriver openBrowser() {
System.setProperty("webdriver.chrome.driver", "drivers/chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
Edit: (dmin_user_can_login() method in LoginTest class)
#Test
public void admin_user_can_login() {
LoginPage l = new LoginPage();
l.GoTo();
l.LoginAs("scenicrail").Login();
//Assert.assertTrue(DashboardPage.IsAt, "Failed to login");
}
LoginPage Class:
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class LoginPage extends Driver {
#Test
public void GoTo() {
openBrowser().get("https://wordpress.com/log-in");
}
public LoginCommand LoginAs(String username) {
return new LoginCommand(username);
}
}

i got an error - java.lang.NullPointerException while running the selenium web driver code block

" Here is the code of selenium web driver in which i use POM design to define all the locators of the web page. So after running the code i got an error regarding the null pointer exception.
"
{
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
By username = By.id("user_login");
By password = By.id("user_pass");
By login = By.id("wp-submit");
By rememberme = By.id("rememberme");
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
public void typepassword(){
driver.findElement(password).sendKeys("demo123");
}
public void clickrememberme(){
driver.findElement(rememberme).click();
}
public void clicklogin(){
driver.findElement(login).click();
}
}
"Here in this code i created an object of a login page and call all the locators using TestNG annotations."
{
package Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Pages.LoginPage;
public class verifylogin {
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\chrome\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
WebDriver driver = null;
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
}
You might want to consider studying scope in java to understand what is happening in this issue. Here is an explanation for what is happening in your case.
In your public void beforetest() method, you're creating a driver, and using it, but when that method is done the driver variable goes out of scope, and you no longer have access to it.
Later, in your verifyValidLogin method, you're creating a new driver variable, and setting it to null:
WebDriver driver = null;
Then you pass this null driver to your LoginPage here:
LoginPage login_test = new LoginPage(driver);//driver is null here
So when you use it here:
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
It's null
Try making these changes:
First, save your driver somewhere when you initialize it like this:
public class verifylogin {
//STORE YOUR DRIVER SOMEWHERE!!! Like here
private WebDriver driver;
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\chrome\\chromedriver.exe");
//Store the driver in the class variable
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
//Now you can use the driver you stored
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
You are removing object reference by using "WebDriver driver = null" in verifyvalidlogin() method. Remove this line and try, it will work.
You instance variable 'driver' as private ('private WebDriver driver').
With 'private' access modifier you can access driver within the class but not from outside, change it to public it will work.
In beforetest() method you are instantiating the browser object and navigating to demo Url.
After that in verifyvalidlogin() method you are making driver object to null and passing this null object to Login page, here you are passing null instead of driver object.
We can solve this issue by declaring driver instance variable inside the class and outside of all methods like below.
WebDriver driver;
Instantiate this driver object in beforetest() method and pass the same driver object to LoginPage without declaring it again as mentioned below.(I executed this script in my local machine its working fine)
package Tests;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import Pages.LoginPage;
public class verifylogin {
WebDriver driver;
#BeforeTest
public void beforetest(){
System.setProperty("webdriver.chrome.driver","C:\\Users\\saniket.soni\\Desktop\\ chrome\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://demosite.center/wordpress/wp-login.php");
}
#Test
public void verifyvalidlogin(){
LoginPage login_test = new LoginPage(driver);
login_test.typeusername();
login_test.typepassword();
login_test.clickrememberme();
login_test.clicklogin();
}
}
package Pages;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class LoginPage {
WebDriver driver;
By username = By.id("user_login");
By password = By.id("user_pass");
By login = By.id("wp-submit");
By rememberme = By.id("rememberme");
public LoginPage(WebDriver driver){
this.driver = driver;
}
public void typeusername(){
driver.findElement(username).sendKeys("admin");
}
public void typepassword(){
driver.findElement(password).sendKeys("demo123");
}
public void clickrememberme(){
driver.findElement(rememberme).click();
}
public void clicklogin(){
driver.findElement(login).click();
}
}
Try this solution and let me know if it works for you.

I want to automate invalid and valid credentials

I am doing Selenium automation with page factory design pattern for a web application. Now I want to do automate valid valid, invalid invalid, valid invalid credential for a login page. How is it?
My complete code is
package com.docmgr.Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.CacheLookup;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.How;
import org.openqa.selenium.WebElement;
public class LoginPage
{
WebDriver driver;
public LoginPage(WebDriver driver)
{
this.driver=driver;
}
#FindBy(how=How.NAME,using="username")
#CacheLookup
WebElement username;
#FindBy(how=How.NAME,using="password")
#CacheLookup
WebElement password;
#FindBy(how=How.CLASS_NAME,using="button")
#CacheLookup
WebElement button;
#FindBy(how=How.LINK_TEXT,using="Forgot Password")
#CacheLookup
WebElement fp;
public void login_Doc(String uid,String pas)
{
username.sendKeys(uid);
password.sendKeys(pas);
button.click();
}
}
package com.docmgr.TestCases;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import com.docmgr.Pages.LoginPage;
import Helper.BrowserFactory;
public class LoginTest
{
#Test
public void chechValidUser()
{
System.setProperty("firefox.webdriver.marionette","pathToGeckodriver");
WebDriver driver=BrowserFactory.startBrowser("firefox","54.68.159.876/docmgr");
LoginPage login=PageFactory.initElements(driver,LoginPage.class);
login.login_Doc("jgsdg","123");
}
}
package Helper;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class BrowserFactory
{
static WebDriver driver;
public static WebDriver startBrowser(String browsName,String url)
{
if(browsName.equals("firefox"))
{
driver=new FirefoxDriver();
}
driver.manage().window().maximize();
driver.get(url);
return driver;
}
}
Pass an extra parameter for login_Doc method which denotes that the give user name and password is valid or not. Look at below example.
public void login_Doc(String uid,String pas,boolean isValidCredential)
{
username.sendKeys(uid);
password.sendKeys(pas);
button.click();
if(isValidCredential == true){
// check if user is logged in successfully and click on logout button
} else {
//check appropriate error message is displayed
}
}
and call the login.login_Doc method as,
login.login_Doc("admin","admin",true); //valid credential
login.login_Doc("admin","admin123",false); //invalid credential
Your tests will look like this:
public class LoginTest
{
#Test
public void chechValidUser()
{
login.login_Doc("valid","valid");
}
#Test
public void chechValidInvalidUser()
{
login.login_Doc("valid","invalid");
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains("Invalid Password"));
}
#Test
public void chechInvalidInvalidUser()
{
login.login_Doc("invalid","invalid");
String bodyText = driver.findElement(By.tagName("body")).getText();
Assert.assertTrue("Text not found!", bodyText.contains("Invalid Username"));
}
}
If you change your login function to this:
public void login_Doc(String uid,String pas)
{
System.setProperty("firefox.webdriver.marionette","pathToGeckodriver");
WebDriver driver=BrowserFactory.startBrowser("firefox","54.68.159.876/docmgr");
LoginPage login=PageFactory.initElements(driver,LoginPage.class);
username.sendKeys(uid);
password.sendKeys(pas);
button.click();
}

Making a java/cucumber Test portable from eclipse

I am a bit new to eclipse and the cucumber/selenium combo. I have three files: a feature, a TestRunner, and the stepDefintion file. I would like to be able to run these files outside of the eclipse IDE. I need to be able to run these tests on a different computer that does not have Eclipse or access to external websites, only the one that will be tested. I've included code for the three sample files (this does not include the proper URL or credentials). I would like to make this somehow executable, however I know that lacking a main method, I can't run this as a Jar.
Feature:
Feature: Login Action
Scenario: Successful Login with Valid Credentials
Given User is on Home Page
When User enters "maximo" and "source1"
Then Message displayed Login Successfully
Scenario: Successful LogOut
When User LogOut from the Application
Then Message displayed LogOut Successfully
TestRunner
package cucumberTest;
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = "Feature"
,glue={"stepDefinition"}
, monochrome = true
, plugin = {"pretty"}
)
public class firstTestCase {
}
And the actual Step Definitions
package stepDefinition;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.interactions.Actions;
import org.openqa.selenium.support.ui.WebDriverWait;
import cucumber.api.java.en.Given;
import cucumber.api.java.en.Then;
import cucumber.api.java.en.When;
public class Test_Steps {
public static WebDriver driver;
private String baseUrl;
static WebDriverWait wait;
#Given("^User is on Home Page$")
public void user_is_on_Home_Page() throws Throwable {
System.setProperty("webdriver.chrome.driver",
"C:\\Selenium\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
baseUrl = "https://maximo-demo76.mro.com/";
wait = new WebDriverWait(driver, 60);
driver.get(baseUrl + "/maximo/webclient/login/login.jsp?welcome=true");
}
// #When("^User Navigate to LogIn Page$")
// public void user_Navigate_to_LogIn_Page() throws Throwable {
// driver.findElement(By.xpath(".//*[#id='account']/a")).click();
// }S
#When("^User enters \"(.*)\" and \"(.*)\"$")
public void user_enters_UserName_and_Password(String realUsername, String realPassword) throws Throwable {
driver.findElement(By.id("username")).clear();
driver.findElement(By.id("username")).sendKeys(realUsername);
driver.findElement(By.id("password")).clear();
driver.findElement(By.id("password")).sendKeys(realPassword);
driver.findElement(By.id("loginbutton")).click();
}
#Then("^Message displayed Login Successfully$")
public void message_displayed_Login_Successfully() throws Throwable {
System.out.println("Login Successfully");
}
#When("^User LogOut from the Application$")
public void user_LogOut_from_the_Application() throws Throwable {
WebElement logOut =
driver.findElement(By.id("titlebar_hyperlink_8-lbsignout_image"));
Actions actions = new Actions(driver);
actions.moveToElement(logOut).click().perform();
}
#Then("^Message displayed LogOut Successfully$")
public void message_displayed_LogOut_Successfully() throws Throwable {
// Write code here that turns the phrase above into concrete actions
System.out.println("LogOut Successfully");
}
}

How to create two object drivers of type WebDriver and use the same Classes and Methods

I have a question related to improving my Selenium Java code. I am really beginner in Java and Selenium either.
I have written a code which I got an example from the internet and adapted to my reality. The coding works fine as described below:
package test;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import page.Login;
public class LoginTest extends BaseTest {
Login login = new Login(driver);
#Test
public void loginWithSuccess() {
sendLoginData("my_user#something.com", "my_password");
login.clickLogin();
assertEquals("View Posted Jobs", login.checkLoginSuccess());
}
private void sendLoginData(String user, String password) {
login.sendUser(user);
login.sendPassword(password);
}
}
The above program is testing and performing a loginWithSucess in the WebSite
package config;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class WebDriverFactory {
public static WebDriver createFirefoxDriver() {
WebDriver driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
return driver;
}
}
In this above example I am instancing a new object WebDriver called driver.
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.openqa.selenium.WebDriver;
import config.WebDriverFactory;
public class BaseTest {
protected static WebDriver driver;
private static boolean setUpIsDone = false;
#BeforeClass
public static void setUp() {
if (setUpIsDone) {
return;
}
// Creating first browser for student login
driver = WebDriverFactory.createFirefoxDriver();
driver.get("http://test-tuitiondesk.rhcloud.com/auth");
driver.manage().window().maximize();
setUpIsDone = true;
}
The above example is where I open my WebSite to authenticate
package page;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
public class Login {
private WebDriver driver;
public Login(WebDriver driver) {
this.driver = driver;
}
public void sendUser(String user) {
driver.findElement(By.xpath("//*[#id='email']")).sendKeys(user);
}
public void sendPassword(String password) {
driver.findElement(By.id("password")).sendKeys(password);
}
public void clickLogin() {
driver.findElement(By.xpath("//*[#id='login-box']/div/div[1]/form/fieldset/div[2]/button")).click();
}
public String checkLoginSuccess() {
return driver.findElement(By.xpath("//a[contains(text(),'View Posted Jobs')]")).getText();
}
}
The above example I have methods which will send a user id and password to the webpage.
So far is everything working fine. The program is performing the following steps:
1 - Open the firefox
2 - Open the webpage
3 - Send the correct user_id, password and click in login button
4 - Check if login was performed with success.
My question now is that I need open a new firefox driver and login with different user_id and this new user_id will interact some actions with the first user_id, so I will need two browsers opened to perform actions with both users in the same time.
I would like to write this implementation the best way than simply write every method again with the second driver. What I thought for the first time was create a new WebDriver called driver2 and create again all methods referring to driver2, but I think I should reuse my methods and classes in a clever way.
Does Anybody have any idea how to implement this second browser in my code?
Thank you
André
You can do this simply by entering this code:
driver2 = WebDriverFactory.createFirefoxDriver();
driver2.get("http://test-tuitiondesk.rhcloud.com/auth");
//call log in function for driver2
//code to interact driver2 with driver1

Categories

Resources