Call java class from a different package - selenium

I want to use an entire java class , to write a test script efficiently . Instead of rewriting it on the class again. Login.java from a diffeerent package from Create_PurchaseReceive.java. I want to use login.java so I wont rewrite in again on Create_purchaseReceive.java.
Tried searching on google and tried calling public void extendbase
login.java
package Login;
public class Login {
WebDriver driver;
//Open Brower
#BeforeTest
public void LoginWebSystem() {
driver = new ChromeDriver();
driver.get("http://localhost:82");
WebElement email = driver.findElement(By.id("login_username"));
email.sendKeys("superadmin");
System.out.println("Username Set");
WebElement password = driver.findElement(By.id("login_password"));
password.sendKeys("nelsoft121586");
System.out.println("Password Set");
WebElement login = driver.findElement(By.id("login_submit"));
login.click();
System.out.println("Login Button Clicked");
}
//If login is successful or failed
#Test (priority=1)
public void LoginAccount() {
String newUrl = driver.getCurrentUrl();
if(newUrl.equalsIgnoreCase("http://localhost:82/controlpanel.php")){
System.out.println("Login Success");
}
else {
System.out.println("Login Failed");
create_purchasereceive.java
package PurchaseModule;
public class Create_PurchaseReceive {
WebDriver driver;
//Open Brower
#BeforeTest
public void LoginWebSystem() {
driver = new ChromeDriver();
driver.get("http://localhost:82");
WebElement email = driver.findElement(By.id("login_username"));
email.sendKeys("superadmin");
System.out.println("Username Set");
WebElement password = driver.findElement(By.id("login_password"));
password.sendKeys("nelsoft121586");
System.out.println("Password Set");
WebElement login = driver.findElement(By.id("login_submit"));
login.click();
System.out.println("Login Button Clicked");
}
//If login is successful or failed
#Test (priority=1)
public void LoginAccount() {
String newUrl = driver.getCurrentUrl();
if(newUrl.equalsIgnoreCase("http://localhost:82/controlpanel.php")){
System.out.println("Login Success");
}
else {
System.out.println("Login Failed");
}
}
//Proceed to Purchase Order page
#Test (priority=2)
public void PurchaseReceivePage() {
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement element = wait.until(
ExpectedConditions.visibilityOfElementLocated(By.partialLinkText("Purchase Receive")));
driver.findElement(By.partialLinkText("Purchase Receive")).click();
System.out.println("Successful in proceeding to Purchase Receive");
}
#Test (priority=3)
public void NewPurchaseRecieve() {
driver.findElement(By.className("bttn-imp-create")).click();
System.out.println("Successful in proceeding to Purchase_receive.php");
String newUrl1 = driver.getCurrentUrl();
if(newUrl1.equalsIgnoreCase("http://localhost:82/purchase.php")){
System.out.println("Successful in proceeding to Purchase Receive page ");
}
else {
System.out.println("Failed in proceeding to Purchase Receive page");
}
}
#Test (priority=4)
public void SelectInvoice() {
driver.findElement(By.id("select-request-invoice")).click();
System.out.println("Successful in clicking select invoice");
WebElement selectinvoice = driver.findElement(By.id("select-request-invoice"));
selectinvoice.click();
}
#Test (priority=6)
public void SearchInvoice() {
WebDriverWait waitdateFROM = new WebDriverWait(driver, 25);
waitdateFROM.until(ExpectedConditions.elementToBeClickable(By.id("date-purchase-from")));
WebElement dateFROM = driver.findElement(By.id("date-purchase-from"));
dateFROM.sendKeys(Keys.chord(Keys.CONTROL, "a"), "2019-09-04",Keys.ENTER);
System.out.println("Successful in changing the date from");
WebElement dateTO = driver.findElement(By.id("date-purchase-to"));
dateTO.sendKeys(Keys.chord(Keys.CONTROL, "a"), "2019-09-05",Keys.ENTER);
System.out.println("Successful in changing the date to");
WebDriverWait waitdateTO = new WebDriverWait(driver, 25);
waitdateTO.until(ExpectedConditions.elementToBeClickable(By.className("bttn-search")));
WebElement searchbutton = driver.findElement(By.className("bttn-search"));
searchbutton.click();
System.out.println("Successful in clicking searchinvoice");
}
}
I expect to use login.java for create_purchasereceive.java

You can extends login class into Create_PurchaseReceive as given below. It may solve your issue.
package PurchaseModule;
public class Create_PurchaseReceive extends Login {
}

Related

Cannot pass from login popup page to password popup page in Selenium

I am trying to create a Selenium test for the account login. Each time when a 'continue' button is clicked it says:
no such element: Unable to locate element:
{"method":"xpath","selector":"//INPUT[#id='password']"}
and remains on the email page, doesn't move to the password page. Though xpath of 'password' textbox is correct. My code is below.
login class
public class login {
WebDriver driver;
public login(WebDriver driver)
{
this.driver = driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//LI[#data-cy='account']")
WebElement CreateorLoginButtonXpath;
#FindBy(xpath="//INPUT[#id='username']")
WebElement EmailTextBoxXpath ;
#FindBy(xpath="//BUTTON[#class='capText font16']")
WebElement ContinueButtonXpath;
#FindBy(xpath="//INPUT[#id='password']")
WebElement PasswordTextBoxXpath;
#FindBy(xpath="//BUTTON[#data-cy='login']")
WebElement LoginButtonXpath;
public void clickCreateorLoginButtonXpath()
{
CreateorLoginButtonXpath.click();
System.out.println("login or create button is clicked");
}
public void TypeEmailTextBoxXpath(String email)
{
EmailTextBoxXpath.sendKeys(email);
System.out.println("email is typed");
}
public void clickContinueButtonXpath()
{
ContinueButtonXpath.click();
System.out.println("Continue Button is clicked");
}
public void TypePasswordTextBoxXpath(String password)
{
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(PasswordTextBoxXpath)).sendKeys(password);
System.out.println("Password is given");
}
public void clickLoginButtonXpath()
{
LoginButtonXpath.click();
System.out.println("Login Button is clicked");
}
}
main class
public class RunloginTestCase {
WebDriver driver = new ChromeDriver();
login lg = new login(driver);
#BeforeTest
public void openBrowser() throws InterruptedException
{
driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);
driver.get("https://www.makemytrip.com/");
System.out.println("Broweser opened");
}
#Test
public void loginTestPositive() throws InterruptedException
{
lg.clickCreateorLoginButtonXpath();
lg.TypeEmailTextBoxXpath("test1992#test.com");
Thread.sleep(2000L);
lg.clickContinueButtonXpath();
driver.manage().timeouts().implicitlyWait(60,TimeUnit.SECONDS) ;
lg.TypePasswordTextBoxXpath("!Qwerqwer1");
lg.clickLoginButtonXpath();
Thread.sleep(3000L);
lg.clickSkipVerificationPopupPageButtonXpath();
}
}
I think you provided a wrong formatted email address. Please try with a valid sample email like "test#test.test" ...
public class RunloginTestCase {
WebDriver driver = new ChromeDriver();
#BeforeTest
public void openBrowser() throws InterruptedException
{
driver.get("https://www.makemytrip.com/");
System.out.println("Broweser opened");
Thread.sleep(3000L);
}
#Test
public void loginTestPositive() throws InterruptedException{
login lg = new login(driver);
lg.clickCreateorLoginButtonXpath();
lg.TypeEmailTextBoxXpath("email");
Thread.sleep(5000L);
lg.clickContinueButtonXpath();
Thread.sleep(5000L);
lg.TypePasswordTextBoxXpath("password");
lg.clickLoginButtonXpath();
}
}
Please try with this one

"No tests found. Nothing was run" message in console , unable to understand why

Below is the code am trying to execute
Not sure why am getting [TestNG] No tests found. Nothing was run
if I remove the before class annotation method, it executes but fails due the dependency
public class TestNG_Practice3 {
static WebDriver driver ;
String url = "https://in.linkedin.com/";
#BeforeClass(description = "To open the browser")
public void openBrowser()
{ driver = new FirefoxDriver();
driver.get(url);
System.out.println("Browser got open");
}
#Test (dependsOnMethods ="openBrowser",description = "To signin")
public void login()
{
driver.manage().timeouts().implicitlyWait(2000, TimeUnit.SECONDS);
WebElement signin = driver.findElement(By.id("login-email"));
Assert.assertTrue(signin.isDisplayed());
WebElement password = driver.findElement(By.id("login-password"));
WebElement signinbutton = driver.findElement(By.id("login-submit"));
signin.sendKeys("xyz");
password.sendKeys("abc");
signinbutton.click();
Assert.assertTrue(driver.getCurrentUrl().contains("feed/"));
}
#Test(dependsOnMethods = "login")
public void logout()
{
WebElement meDropdown = driver.findElement(By.xpath("//*[#id=\"nav-settings__dropdown-trigger\"]/div/span[2]/li-icon/svg"));
meDropdown.click();
WebElement logout = driver.findElement(By.id("ember545"));
logout.click();
}
#AfterClass
public void closebrowser()
{
driver.quit();
}
}
Step-1 : Basic trial with Project Build,
public class TestNG_Demo {
#BeforeClass
public void openbrowser()
{
System.out.println("Browser got open");
}
#Test
public void testbrowser()
{
System.out.println("Test execution");
}
#AfterClass
public void closebrowser()
{
System.out.println("Browser got close");
}
}
So you will be have idea, Your project build get successful execution.
If you have maven project and Build did not get pass, you will be have trigger what is causing from maven build dependency.
Update
Step-2 : After tracing first trial
public class TestNG_Demo {
#Test
public void testbrowser()
{
WebDriver driver = new FirefoxDriver();
driver.get("http://google.com");
}
}
Remove dependsOnMethods ="openBrowser" because it's not a test method and will be execute before test without it

Unable to load chrome/gecko driver after using Cucumber Driver Factory

This is my first question ever asked here, so I hope I ask it the right way:
I'm working on a multimodule maven project to test a software that is still in a development. I've been using Cucumber, Selenium, JUnit for some time and doing online courses to improve my skills. In one of the tutorials was explained how to use Driver Factory and configuration files so I applied it to my project, but after that was unable to run any of the drivers (gecko/chrome/ie). Here is a big part of the code, so I hope someone can help :)
I catch the exception from the DriverFactory.class:
"Unable to load browser: null"
config.properties file has only one line:
browser=chrome
public class DriverFactory {
public static WebDriver driver;
public WebDriver getDriver() {
try {
//Read Config
ReadConfigFile file = new ReadConfigFile();
String browserName = file.getBrowser();
switch (browserName) {
case "firefox":
if (driver == null) {
System.setProperty("webdriver.gecko.driver", Constant.GECKO_DRIVER_DIRECTORY);
FirefoxOptions options = new FirefoxOptions();
options.setCapability("marionette", false);
driver = new FirefoxDriver(options);
driver.manage().window().maximize();
}
break;
case "chrome":
if (driver == null) {
System.setProperty("webdriver.chrome.driver", Constant.CHROME_DRIVER_DIRECTORY);
driver = new ChromeDriver();
driver.manage().window().maximize();
}
break;
/*case "ie":
if (driver == null) {
DesiredCapabilities capabilities = DesiredCapabilities.internetExplorer();
System.setProperty("webdriver.ie.driver", Constant.IE_DRIVER_DIRECTORY);
capabilities.setCapability("ignoreZoomSetting", true);
driver = new InternetExplorerDriver(capabilities);
driver.manage().window().maximize();
}
*/
}
} catch (Exception e) {
System.out.println("Unable to load browser: " + e.getMessage());
} finally {
driver.manage().timeouts().pageLoadTimeout(60, TimeUnit.SECONDS);
}
return driver;
}
public class ReadConfigFile {
protected InputStream input = null;
protected Properties prop = null;
public ReadConfigFile() {
try {
input = ReadConfigFile.class.getClassLoader().getResourceAsStream(Constant.CONFIG_PROPERTIES_DIRECTORY);
prop = new Properties();
prop.load(input);
} catch(IOException e) {
e.printStackTrace();
}
}
public String getBrowser() {
if(prop.getProperty("browser") == null) {
return "";
}
return prop.getProperty("browser");
}
public class Constant {
public final static String CONFIG_PROPERTIES_DIRECTORY = "properties\\config.properties";
public final static String GECKO_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\geckodriver.exe";
public final static String CHROME_DRIVER_DIRECTORY = System.getProperty("user.dir") + "\\src\\test\\resources\\chromedriver.exe";
public class CreateCaseSteps extends DriverFactory {
//Background Steps
#Given("^user accesses the login page$")
public void userAccessesTheLoginPage() throws Throwable {
getDriver().get("http://localhost:8080/");
}
#When("^user enters a valid username")
public void userEntersAValidUsername(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='username']")).sendKeys(data.get(0).get(0));
}
#When("^user enters a valid password")
public void userEntersAValidPassword(DataTable table) throws Throwable {
Thread.sleep(3000);
List<List<String>> data = table.raw();
getDriver().findElement(By.xpath("//input[#placeholder='password']")).sendKeys(data.get(0).get(0));
}
#And("^user clicks on the login button$")
public void userClicksOnTheLoginButton() throws Throwable {
getDriver().findElement(By.xpath("//input[#value='Login']")).click();
}
#Then("^user should be taken successfully to the login page$")
public void userShouldBeTakenSuccessfullyToTheLoginPage() throws Throwable {
Thread.sleep(3000);
WebElement logoutMenu = getDriver().findElement(By.xpath("//i[#class='glyphicon glyphicon-user']"));
Assert.assertEquals(true, logoutMenu.isDisplayed());
}

Running selenium, cucumber and Page Factory. Second step definition fail to run

I wrote a cucumber framework that has two feature files and two stepdefinitions which are glued to the feature files. When i run the test together, it ran for the first stepDefinition and fail to enter the second stepDefinition. I have initialize my pages and yet couldn't get it to work.
Error and Codes below
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.$Proxy19.click(Unknown Source)
at Pages.HomePage.CreateANewOrderPage.createOrderLink(CreateANewOrderPage.java:35)
at StepDefinitions.CreateOrderStep.user_click_on_create_a_new_order(CreateOrderStep.java:24)
at ✽.When user click on create a new order(CreateOrder.feature:5)
public class CreateANewOrderPage {
WebDriver driver;
public CreateANewOrdePage(WebDriver driver){
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy (linkText= "Create a new order")
public WebElement createOrderLink;
public void createOrderLink(){
createOrderLink.click();
}
public class SigninPage {
WebDriver driver;
public SigninPage(WebDriver driver) {
this.driver=driver;
PageFactory.initElements(driver, this);
}
#FindBy(xpath="//*[#id=\"userName\"]")
public WebElement usernameField;
#FindBy(name="password")
public WebElement passwordField;
#FindBy(id="buttonSubmitLogin")
public WebElement submitBtn;
public void loginDetails(String uname, String psw) {
usernameField.sendKeys(uname);
passwordField.sendKeys(psw);}
public void clickLogin(){
submitBtn.click();
}
}
public class SigninStep {
WebDriver driver;
SigninPage logIn = new SigninPage(driver);
#Given("^user navigates to mySite$")
public void userNavigatesToMysite() throws Throwable {
System.setProperty("webdriver.chrome.driver", "C:\\Users\\mypc\\Documents\\Automation\\drivers\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("www.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
}
#And("^user enter \"([^\"]*)\" and \"([^\"]*)\"$")
public void userEnterValidCredentials(String validuname, String validpsw) throws Throwable {
SigninPage logIn = new SigninPage(driver);
logIn.loginDetails("jdjdjdj","jjdjdj");
}
#When("^user click on Sign in$")
public void userClickSignIn() throws Throwable {
SigninPage logIn = new SigninPage(driver);
logIn.clickLogin();
}
}
public class CreateOrderStep {
WebDriver driver;
CreateANewOrderPage ordercreate;
#When("^user click on create a new order$")
public void user_click_on_create_a_new_order() throws Throwable {
ordercreate= PageFactory.initElements(driver,CreateANewOrderPage.class);
ordercreate.createOrderLink();
}
#RunWith(Cucumber.class)
#CucumberOptions (features = "src\\test\\java\\Features\\",
glue ={"StepDefinitions"},
tags={"#Signin, #CreateOrder"}
//format = {"pretty", "html:target/Destination.."}
// format={"json:target/Destination/cucumber.json"
)
public class SigninRunner {
}

How to Set up POM Structure using selenium java and (TestNG Framework)

I'm new for QA automation and I have average knowledge in java,
so I decided to use (Selenium+Java) to do automation.
I will attach the code I did to the automation.and the script runs smoothly.
But the Structure I did is incorrect as I want to follow the (POM-Selenium).POM-Page Oriented Model
This Script navigates as Follows
Login(Page)-->Peronal(Drop/down Selection)--->AddEdit((Drop/down Selection))-->Personal(Page)-->Add(Button)-->PersonalDetails(Page)
The test scenario is......
the user should "login" to the system, and have to click "personal" drop down in the navigation tab then there will be an "AddEdit" drop downselection.then the user is directed to the page titled as "personal", the user should click "Add" button on that page to get directed to another page called "personal Details" user can add the relevant fields which are provided from the page to add a new Client.
Please help me to arrange this to POM Structure.because I'm having very hard time to think how it goes.what frustrates me is in order user to add a relevant record he/she should be logged in to the system and in POM it says login is a separate page I have to navigate through three pages to complete the task.it would be great if you can help me out.and it's open to discussion and sorry if my English is bad. and please consider me as a total noob when it comes to automation :) thanks!
This is the Test Script I wrote...
package TestNG;
import java.util.Iterator;
import java.util.List;
import javax.swing.JOptionPane;
import org.openqa.selenium.*;
import org.openqa.selenium.By.ByXPath;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;
import org.testng.annotations.*;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
//public String baseUrl;
//public String driverPath;
//public WebDriver driver;
public class Tester {
public String baseUrl = "http://xxx.xxx.xxx.xxx:xxxx/xxx/";
public String driverPath = "C:\\Users\\User\\Desktop\\geckodriver.exe";
public WebDriver driver;
#Test(priority = 0)
public void Login() {
System.out.println("launching firefox browser");
System.setProperty("webdriver.gecko.driver", driverPath);
driver = new FirefoxDriver();
driver.get(baseUrl);
WebElement username = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id=\"userId\"]")));
username.sendKeys("xxxxxxxxx");
WebElement password = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id=\"loginPassword\"]")));
password.sendKeys("xxxxxxxxxxxxxxxxxx");
WebElement button = (new WebDriverWait(driver, 10)).until(ExpectedConditions
.presenceOfElementLocated(By.xpath("/html/body/div/div[3]/div/div/form/div[3]/div[2]/div/button")));
button.click();
String expectedTitle = "xxxxxxxxxxxxxxxxxxxxxxxx";
String actualTitle = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("/html/body/div[2]/div[2]/div/div/h1")))
.getText().toString();
// System.out.println(actualTitle);
Assert.assertEquals(actualTitle, expectedTitle);
// driver.close();
}
#Test(priority = 1)
public void Personal_Tab_Selection() {
clickWhenReady("/html/body/div[2]/div[2]/nav/div/div[2]/div/div[1]/ul/li[5]/a", 10, driver);
}
#Test(priority = 2)
public void Add_Edit_Selection() {
clickLinkByHref("/rsa/5/15/staff/n/i/list", driver);
}
#Test(priority = 3)
public void Add_Button() {
clickWhenReady("/html/body/div[2]/div[2]/div/div[2]/form/div[2]/div/div/a", 10, driver);
}
#Test(priority = 4)
public void Radio_Button_AMW() {
WebElement amw_radio = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[1]/div/div/label[1]")));
amw_radio.click();
}
#Test(priority = 5)
public void Radio_Button_service_provider() {
WebElement service_provider = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[2]/div/div/label[1]")));
service_provider.click();
}
#Test(priority = 6)
public void Service_Provider_Name_select() {
WebElement Service_Provider_DD = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[3]/div/div/a")));
Service_Provider_DD.click();
driver.findElement(By.cssSelector("ul > li:nth-child(2)")).click();
}
#Test(priority = 7)
public void Employee_Code_Enter() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[5]/div/input"))
.sendKeys("01112");
}
#Test(priority = 8)
public void Click_Salutation() {
WebElement Salutation_DD = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[6]/div/div/a")));
Salutation_DD.click();
}
#Test(priority = 9)
public void Salutation_Click() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[6]/div/div/div/ul/li[5]"))
.click();
}
#Test(priority = 10)
public void employee_name() {
WebElement empname = driver
.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[7]/div/input"));
empname.sendKeys("Test2");
}
#Test(priority = 11)
public void Sap_plant_code() {
WebElement plant_code = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[8]/div/div/a")));
plant_code.click();
}
#Test(priority = 12)
public void sap_code_set() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[8]/div/div/div/ul/li[3]"))
.click();
}
#Test(priority = 13)
public void sap_vendor_code() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[9]/div/input"))
.sendKeys("test_2");
}
#Test(priority = 14)
public void employee_role_select() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[10]/div/div/ul")).click();
}
#Test(priority = 15)
public void select_Technician_role() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[10]/div/div/div/ul/li"))
.click();
}
#Test(priority = 16)
public void select_status() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[11]/div/div/a")).click();
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[11]/div/div/div/ul/li[1]"))
.click();
}
#Test(priority = 17)
public void click_save_button() {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[2]/div/div/button[1]")).click();
}
#Test(priority = 18)
public void Record_add_notification_Check() {
if ((new WebDriverWait(driver, 10)).until(ExpectedConditions
.presenceOfElementLocated(By.xpath("/html/body/div[2]/div[3]/div/div/button"))) != null) {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/div/div/button")).click();
} else {
infoBox("not Added", "Not Added");
}
}
public static void infoBox(String infoMessage, String titleBar) {
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
public static void clickWhenReady(String location, int timeout, WebDriver driver) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(driver, timeout);
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(location)));
element.click();
}
public static void clickLinkByHref(String href, WebDriver driver) {
List<WebElement> anchors = driver.findElements(By.tagName("a"));
Iterator<WebElement> i = anchors.iterator();
while (i.hasNext()) {
WebElement anchor = i.next();
if (anchor.getAttribute("href").contains(href)) {
anchor.click();
break;
}
}
}
}
A few words about your script:
presenceOfElementLocated(By.xpath("//*[#id=\"userId\"]")) - If an element have an id you should always try to use id instead of xpath
By.xpath("/html/body/div/div[3]/div/div/form/div[3]/div[2]/div/button")) - It is recommended to use logical xpath instead of absolute xpath as much as possible. Else your xpath becomes vulnerable.
Now as you are willing to follow the POM, you need to define all the elements of a page in a single page which will be called the PageFactory. Likewise, all the Elements of a webpage will reside in separate class.
For e.g. an entry for an element on a webpage may look like:
#FindBy(id="user_login")
WebElement username;
As you are using TestNG, you can move the Browser related code to a seperate class Browserfactory. From your test class, within #BeforeTest Annotation call the methods of Browserfactory to initialize the browser, open the url.
These are some of the basic steps to implement your code through POM.
Let me know if this solves your query.
These are the classes I created depending on the pages of UI,ill attach the structure as a snapshot too :)
public class Driver_class {
private static String baseUrl;
private static String driverPath;
public static WebDriver driver;
public static WebDriver getDriver() {
baseUrl = "http://xxx.xxx.xxx.xxx:xx:xx\\Desktop\\geckodriver.exe";
if (driver == null) {
System.setProperty("webdriver.gecko.driver", "C:\\Users\\User\\Desktop\\geckodriver.exe");
driver = new FirefoxDriver();
driver.get(baseUrl);
}
return driver;
}
}
public class Login {
public WebElement uid;
public WebElement pwd;
public WebElement loginbtn;
public void get_elements(WebDriver driver) {
uid = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id=\"userId\"]")));
pwd = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id=\"loginPassword\"]")));
loginbtn = (new WebDriverWait(driver, 10)).until(ExpectedConditions
.presenceOfElementLocated(By.xpath("/html/body/div/div[3]/div/div/form/div[3]/div[2]/div/button")));
}
public void customerLogin() {
this.uid.sendKeys("xxxxxxxx");
this.pwd.sendKeys("xxxxxxxxxxx");
this.loginbtn.click();
}
}
public class Navigation {
public WebElement Personal_Tab;
public WebElement Add_Edit_p;
public void navigate_personal_button(WebDriver driver) {
clickWhenReady("/html/body/div[2]/div[2]/nav/div/div[2]/div/div[1]/ul/li[5]/a", 10, driver);
}
public void navigate_personal_add_button(WebDriver driver) {
clickLinkByHref("/rsa/5/15/staff/n/i/list", driver);
}
public static void clickWhenReady(String location, int timeout, WebDriver driver) {
WebElement element = null;
WebDriverWait wait = new WebDriverWait(driver, timeout);
element = wait.until(ExpectedConditions.elementToBeClickable(By.xpath(location)));
element.click();
}
public void clickLinkByHref(String href, WebDriver driver) {
List<WebElement> anchors = driver.findElements(By.tagName("a"));
Iterator<WebElement> i = anchors.iterator();
while (i.hasNext()) {
WebElement anchor = i.next();
if (anchor.getAttribute("href").contains(href)) {
anchor.click();
break;
}
}
}
}
public class Personal_Details {
WebElement amw_radio;
WebElement service_provider;
WebElement Service_Provider_DD;
//WebElement Employee_Code_Enter;
WebElement Click_Salutation;
WebElement Salutation_DD;
WebElement empname;
WebElement plant_code;
//WebElement
public void Radio_Button_AMW(WebDriver driver) {
amw_radio = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[1]/div/div/label[1]")));
amw_radio.click();
}
public void Radio_Button_service_provider(WebDriver driver) {
service_provider = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[2]/div/div/label[1]")));
service_provider.click();
}
public void Service_Provider_Name_select(WebDriver driver) {
Service_Provider_DD = (new WebDriverWait(driver, 10))
.until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[3]/div/div/a")));
Service_Provider_DD.click();
driver.findElement(By.cssSelector("ul > li:nth-child(2)")).click();
}
public void Employee_Code_Enter(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[5]/div/input"))
.sendKeys("01112");
}
public void Click_Salutation(WebDriver driver) {
Salutation_DD = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[6]/div/div/a")));
Salutation_DD.click();
}
public void Salutation_Click(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[6]/div/div/div/ul/li[5]"))
.click();
}
public void employee_name(WebDriver driver) {
empname = driver
.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[7]/div/input"));
empname.sendKeys("Test2");
}
public void Sap_plant_code(WebDriver driver) {
plant_code = (new WebDriverWait(driver, 10)).until(ExpectedConditions.presenceOfElementLocated(
By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[8]/div/div/a")));
plant_code.click();
}
public void sap_code_set(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[8]/div/div/div/ul/li[3]"))
.click();
}
public void sap_vendor_code(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[9]/div/input"))
.sendKeys("test_2");
}
public void employee_role_select(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[10]/div/div/ul")).click();
}
public void select_Technician_role(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[10]/div/div/div/ul/li"))
.click();
}
public void select_status(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[11]/div/div/a")).click();
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[1]/div[11]/div/div/div/ul/li[1]"))
.click();
}
public void click_save_button(WebDriver driver) {
driver.findElement(By.xpath("/html/body/div[2]/div[2]/div/div[2]/form/div[2]/div/div/button[1]")).click();
}
public void Record_add_notification_Check(WebDriver driver) {
if ((new WebDriverWait(driver, 10)).until(ExpectedConditions
.presenceOfElementLocated(By.xpath("/html/body/div[2]/div[3]/div/div/button"))) != null) {
driver.findElement(By.xpath("/html/body/div[2]/div[3]/div/div/button")).click();
} else {
infoBox("not Added", "Not Added");
}
}
public static void infoBox(String infoMessage, String titleBar) {
JOptionPane.showMessageDialog(null, infoMessage, "InfoBox: " + titleBar, JOptionPane.INFORMATION_MESSAGE);
}
}
public class Personal_list {
WebElement add_btn;
public void find_add_btn(WebDriver driver) {
String add_btn_path = "/html/body/div[2]/div[2]/div/div[2]/form/div[2]/div/div/a";
detect_element_click(driver, add_btn_path);
}
public void detect_element_click(WebDriver webDriver, String xp) {
WebDriverWait wait = new WebDriverWait(webDriver, 10);
wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath(xp))).click();
}
}
This is the TestCaseClass Which executes all test_cases
public class TestCases {
public WebDriver driver = Driver_class.getDriver();
#Test(priority = 0)
public void newCustomerLogin() {
Login rsaLogin = PageFactory.initElements(driver, Login.class);
rsaLogin.get_elements(driver);
rsaLogin.customerLogin();
}
#Test(priority = 1)
public void click_Personal_tab() {
Navigation n = PageFactory.initElements(driver, Navigation.class);
n.navigate_personal_button(driver);
n.navigate_personal_add_button(driver);
}
#Test(priority=2)
public void click_add_tab() {
Personal_list ps= PageFactory.initElements(driver,Personal_list.class);
ps.find_add_btn(driver);
}
#Test(priority=3)
public void Enter_personal_details(){
Personal_Details d= new Personal_Details();
d.Radio_Button_AMW(driver);
d.Radio_Button_service_provider(driver);
d.Service_Provider_Name_select(driver);
d.Employee_Code_Enter(driver);
d.Click_Salutation(driver);
d.Salutation_Click(driver);
d.employee_name(driver);
d.Sap_plant_code(driver);
d.sap_code_set(driver);
d.sap_vendor_code(driver);
d.employee_role_select(driver);
d.select_Technician_role(driver);
d.select_status(driver);
d.click_save_button(driver);
d.Record_add_notification_Check(driver);
}
}