How to use same object across packages - java

I have 2 packages, 1st the Base package package ceccms.automation.framework and another package package ceccms.testcases as follows:
package ceccms.automation.framework;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.edge.EdgeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class UniversalMethods {
public static WebDriver driver = null;
public static String chromepath = "D:\\Automation\\Web Drivers\\ChromeDriver\\chromedriver.exe";
public static String edgepath = "D:\\Automation\\Web Drivers\\EdgeDriver\\MicrosoftWebDriver.exe";
public WebDriver openBrowser (String browser, String url) {
if (browser != null) {
switch (browser) {
case "Mozilla":
driver = new FirefoxDriver();
driver.get(url);
break;
case "Chrome":
System.setProperty("webdriver.chrome.driver", chromepath);
driver = new ChromeDriver();
driver.get(url);
break;
case "Edge":
System.setProperty("webdriver.edge.driver", edgepath);
driver = new EdgeDriver();
driver.get(url);
break;
default:
System.out.println("Wrong Browser Name");
driver.quit();
}
}
driver.manage().window().maximize();
return driver;
}
}
and
package ceccms.testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import ceccms.automation.framework.UniversalMethods;
public class LoginTest {
public static String url = "https://test.ceccms.com/Login.aspx?";
static UniversalMethods U = new UniversalMethods();
public static void main(String[] args) throws InterruptedException {
String browserName = "Chrome";
U.openBrowser(browserName, url);
WebElement userName = driver.findElement(By.id("txtUserName"));
userName.sendKeys("pkumar");
WebElement password = driver.findElement(By.id("txtUserPass"));
password.sendKeys("PassMe33");
Thread.sleep(3000);
driver.quit();
}
}
I am running the code through the second package. I want to use one object driver across the package without using the notation U.driver.findElement() . How can I achieve that ?

One of the solutions, you can add Page Objects, where define Web elements and give your Driver as parameter to initiate Page object class with all web elements. This will allow you to work directly with elements.

You can use it, with this structure(By extending universal method):
package ceccms.testcases;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import ceccms.automation.framework.UniversalMethods;
public class LoginTest extends UniversalMethods {
//You can access driver and method without using object reference
public static String url = "https://test.ceccms.com/Login.aspx?";
public static void main(String[] args) throws InterruptedException {
String browserName = "Chrome";
openBrowser(browserName, url);
WebElement userName = driver.findElement(By.id("txtUserName"));
userName.sendKeys("pkumar");
WebElement password = driver.findElement(By.id("txtUserPass"));
password.sendKeys("PassMe33");
Thread.sleep(3000);
driver.quit();
}
}

Related

How to solve the error of data provider if only one browser is taking the complete input data?

I'm trying to achieve parallel execution through data provider, but unable to do it. can someone help me with this.
The error is two browsers are opening but the data is going to only one browser.
Here, is my program code:
package PracticePrograms;
import java.time.Duration;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import io.github.bonigarcia.wdm.WebDriverManager;
public class DataProviderSample1{
public WebDriver driver;
#BeforeMethod
public void setUp() throws InterruptedException {
WebDriverManager.firefoxdriver().setup();
driver = new FirefoxDriver();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(6));
driver.get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");
}
#Test(dataProvider = "inputData")
public void testLogin(String UserName, String Password ) throws InterruptedException {
driver.findElement(By.name("username")).sendKeys(UserName);
driver.findElement(By.name("password")).sendKeys(Password);
driver.findElement(By.xpath("//button[#type='submit']")).click();
}
#DataProvider(name = "inputData", parallel = true)
public static Object[][] loginData() {
Object[][] data = new Object[2][2];
data[0][0] = "Admin";
data[0][1] = "admin123";
data[1][0] = "admin";
data[1][1] = "admin123";
return data;
}
#AfterMethod
public void tear_down() throws InterruptedException {
driver.quit();
}
}
I appreciate u r help on this.
Despite your method logic runs in parallel all your threads still use the same instance of your test class. Hence they share the same instance of your driver field.
This leads to the case when the setUp() executed "after" overwrites the value set by setUp that has been executed "before"..
So to overcome this you need to introduce ThreadLocal variable. Instead of public WebDriver driver; you would have ThreadLocal<WebDriver> driver = new ThreadLocal<>();
Now instead of driver = new FirefoxDriver(); you would have driver.set( new FirefoxDriver());
After you have set that driver to ThreadLocal, wherever you obtain its value you have to do driver.get(). For example:
driver.get().manage().deleteAllCookies();
driver.get().manage().timeouts().implicitlyWait(Duration.ofSeconds(6));
driver.get().get("https://opensource-demo.orangehrmlive.com/web/index.php/auth/login");

NullPointerException in Selenium WebDriver

I'm a beginner Selenium practitioner. I have 2 classes, one for the WebDriver another is for Log In. I followed some youtube tutorials but can't pinpoint what I'm doing wrong. I tried the concept of 'Baseclass' where I extend the other class.
LogIn Class
WebDriver Class
If I add the WebDriver in the other class, it will run successfully. But I want to make it more 'organized'
this is the error
Error message
public Webdriver driver;
Please add static in this line
public static Webdriver driver;
because you need use same driver instance for all classes
create above line in top of both classes
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.chrome.ChromeOptions;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.nio.file.Paths;
public class TestApp {
private WebDriver driver;
private static TestApp myObj;
// public static WebDriver driver;
utils.PropertyFileReader property = new PropertyFileReader();
public static TestApp getInstance() {
if (myObj == null) {
myObj = new TestApp();
return myObj;
} else {
return myObj;
}
}
//get the selenium driver
public WebDriver getDriver()
{
return driver;
}
//when selenium opens the browsers it will automatically set the web driver
private void setDriver(WebDriver driver) {
this.driver = driver;
}
public static void setMyObj(TestApp myObj) {
TestApp.myObj = myObj;
}
public void openBrowser() {
//String chromeDriverPath = property.getProperty("config", "chrome.driver.path");
//String chromeDriverPath = property.getProperty("config", getChromeDriverFilePath());
System.setProperty("webdriver.chrome.driver", getChromeDriverFilePath());
ChromeOptions options = new ChromeOptions();
options.addArguments("--disable-notifications");
options.addArguments("disable-infobars");
driver = new ChromeDriver(options);
driver.manage().window().maximize();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void navigateToURL() {
String url =property.getProperty("config","url");
;
driver.get(url);
}
public void closeBrowser()
{
driver.quit();
}
public WebElement waitForElement(By locator, int timeout)
{
WebElement element = new WebDriverWait(TestApp.getInstance().getDriver(), timeout).until
(ExpectedConditions.presenceOfElementLocated(locator));
return element;
}
private String getChromeDriverFilePath()
{
// checking resources file for chrome driver in side main resources
URL res = getClass().getClassLoader().getResource("chromedriver.exe");
File file = null;
try {
file = Paths.get(res.toURI()).toFile();
} catch (URISyntaxException e) {
e.printStackTrace();
}
return file.getAbsolutePath();
}
}
//create package name called utils and under that package create class name with TestApp and paste above code
if you want use driver anywhere in your project
TestApp.getInstance().getdriver();
You didn't initialize your driver anywhere.
You need to use a before
#BeforeClass
public void setupClass(){
driver = new Chromedriver();
}
and in opensite
public static WebDriver driver;
You want your OpenSite class to act as the base class which you can extend it to your test class to intialize your driver. Remove your "#test" annotaion from the OpenSite class.
Add static with "public WebDriver driver";
Create a method openBrowser(already there) or driverInitialization in this class.
Return the driver instance.
Updated code will look like
public class OpenSite{
public static WebDriver driver;
public static void openBrowser(){
System.setProperty("webdriver","path");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("your URL");
return driver;
}
}
And in test class LogIn extend this class and call this method:
public class LogIn extends OpenSite{
#BeforeTest
public void driver initialization(){
openBrowser();
}
#Test
public void logInVendor(){
//Write your code here
}
}

Tests using Page Factory Design and Page Object Model opens two instances of the browser using Selenium and Java

I have a test in Selenium WebDriver with Page Object Model, if I run the following test open two windows in the Chrome browser, first window is empty in a URL line. How I can opening only one with onet.pl URL?
I trying deleting initialize Chrome driver but will have null.exception error.
What am I doing wrong?
package Pages;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.FindBy;
public class LoginPage {
private WebDriver driver;
//private WebDriverWait wait;
public LoginPage() {
this.driver = new ChromeDriver();
//wait = new WebDriverWait(driver,10);
}
#FindBy(xpath="//div[#class='col-md-12']//form")
private WebElement loginForm;
#FindBy(id="username")
private WebElement loginField;
#FindBy(id="password")
private WebElement passwordField;
#FindBy(xpath="//button[#class='btn btn-multisport-default btn-multisport-large btn-full-width login-button']")
private WebElement buttonLogin;
public void open() {
driver.get("https://onet.pl");
}
public void enterLogin() {
String login = "vadim1234#test.pl";
loginField.sendKeys(login);
}
public void enterPassword() {
String password = "Benefit!";
passwordField.sendKeys(password);
}
public void login() {
buttonLogin.click();
}
}
And test code:
import Pages.Dashboard;
import Pages.LoginPage;
import org.junit.jupiter.api.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.PageFactory;
import java.util.concurrent.TimeUnit;
public class LogIn {
#Test
public void correctLogin() {
System.setProperty("webdriver.chrome.driver", "src/main/resources/chromedriver.exe");
WebDriver driver = new ChromeDriver();
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
loginPage.open();
loginPage.enterLogin();
loginPage.enterPassword();
loginPage.login();
driver.close();
driver.quit();
Dashboard dashboard = new Dashboard(driver);
dashboard.getLoggedUser();
}
}
From your test class as you are passing the reference of the driver:
LoginPage loginPage = PageFactory.initElements(driver, LoginPage.class);
In LoginPage class, within the constructor, instead of:
public LoginPage() {
this.driver = new ChromeDriver();
//wait = new WebDriverWait(driver,10);
}
you need to do reuse the instance passed as follows:
public LoginPage(WebDriver loginPageDriver) {
this.driver=loginPageDriver;
}
That would solve the issue of 2 browsers getting opened.
References
You can find a couple of relevant detailed discussions in:
Selenium [Java] PageFactory Design : Where do I write my Assertions following Page Object Model

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);
}
}

Cannot instantiate the type FirefoxDriver

Can seem to make this code execute. Compiler isn't instantiating the driver. what can I do to correct this.
package mypackage;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
org.openqa.selenium.support.ui.ExpectedConditions;
import
org.openqa.selenium.support.ui.WebDriverWait;
public class selenium {
public static void main(String[] args) {
WebDriver driver = (WebDriver) new FirefoxDriver();
WebDriverWait MyWaitlVar= new
WebDriverWait(driver, 10);
String baseUrl =
"http://newtours.demoaut.com";
String expectedTitle = "Welcome: Mercury Tours";
String actualTitle = "";
// launch Firefox and direct it to the Base URL
driver.get(baseUrl);
// get the actual value of the title
actualTitle = driver.getTitle();
/*
* compare the actual title of the page
witht the expected one and print
* the result as "Passed" or "Failed"
*/
if (actualTitle.contentEquals
(expectedTitle)){
System.out.println("Test Passed!");
} else {
System.out.println("Test Failed");
}
//close Firefox
driver.close();
// exit the program explicitly
System.exit(0);
}
}

Categories

Resources