Need to identify the ancestor of the mentioned web element - selenium

New to Selenium. Been doing some activity but getting stuck every now and then.
Plus if there is any error, at times it is not showing me the error. Below is my query.
Address Book is a page that stores address.
URL: http://webapps.tekstac.com/AddressBook/
This is the procedure:
Invoke the driver using getWebDriver() method defined in DriverSetup().
Navigate to "http://webapps.tekstac.com/AddressBook/".
Identify ancestor of the 'Nick Name' label text. That is the ancestor 'div' of the form. Get the text of this ancestor and store it in a static variable fName.
This is the code for which I am 66.67% evaluated.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class NameLocator //DO NOT Change the class name
{
//Use the declared variables for stroing required values
static String fName;
static String baseUrl;
static WebDriver driver;
public WebDriver setupDriver() //DO NOT Change the method Signature
{
DriverSetup ds = new DriverSetup();
return ds.getWebDriver();
/* Replace this comment by the code statement to create and return the driver */
/* Naviaget to the url 'http://webapps.tekstac.com/AddressBook/' */
}
public String getNameLocator() //DO NOT Change the method Signature
{
WebElement element = driver.findElement(By.xpath("//div[.//[text()='NickName']]/ancestor::div"));
fName = element.getText();
driver.close();
return fName;
/*Using the driver, Find the element ancestor and its text and assign the text to 'fName' */
/*Close the driver*/
}
public static void main(String[] args)
{
NameLocator namLocator=new NameLocator();
//Add required code here
}
}
Error while compiling: Ancestor's div text is not correct.
THIS IS HOW THE ORIGINAL TEMPLATE LOOKED BEFORE I STARTED FILLING UP THE CODE. THIS IS HOW THEY HAVE DESIGNED THE ACTIVITY AND THE COMMENTS WERE NOT MANUALLY ENTERED BY ME.
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
public class NameLocator //DO NOT Change the class name
{
//Use the declared variables for stroing required values
static String fName;
static WebDriver driver;
public WebDriver setupDriver() //DO NOT Change the method Signature
{
/* Replace this comment by the code statement to create and return the driver */
/* Naviaget to the url 'http://webapps.tekstac.com/AddressBook/' */
}
public String getNameLocator() //DO NOT Change the method Signature
{
/*Using the driver, Find the element ancestor and its text and assign the text to 'fName' */
/*Close the driver*/
}
public static void main(String[] args)
{
NameLocator namLocator=new NameLocator();
//Add required code here
}
}

Code according to the comments. Screenshot with result is here image link:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
public class NameLocator {
static String fName;
static WebDriver driver;
public WebDriver setupDriver() //DO NOT Change the method Signature
{
/* Replace this comment by the code statement to create and return the driver */
/* Naviaget to the url 'http://webapps.tekstac.com/AddressBook/' */
System.setProperty("webdriver.chrome.driver", "d:\\Downloads\\chromedriver\\chromedriver.exe");
driver = new ChromeDriver();
driver.get("http://webapps.tekstac.com/AddressBook/");
return driver;
}
public String getNameLocator() //DO NOT Change the method Signature
{
/*Using the driver, Find the element ancestor and its text and assign the text to 'fName' */
/*Close the driver*/
WebElement element = driver.findElement(By.xpath("//*[text()='NickName']/ancestor::div"));
fName = element.getText();
driver.quit();
return fName;
}
public static void main(String[] args) {
NameLocator namLocator = new NameLocator();
//Add required code here
namLocator.setupDriver();
namLocator.getNameLocator();
System.out.println(fName);
}
}

Related

Selenium - Use text string in several TestNG #Test-annotations

I have a text string tag i grab with getText.
Then i want to use that string in another #Test
I have tried to put it in #BeforeSuite but can't make that to work either?
Can you please assist...:)
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;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class values_test {
static WebDriver driver;
#BeforeTest
public void setup() throws Exception {
driver = new HandelDriver().getDriver("CHROME");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://chercher.tech/selenium-webdriver-sample");
}
#Test (priority = 100)
public void GetText() throws IOException {
// fetches text from the element and stores it in text
String text = driver.findElement(By.xpath("//li[#class='breadcrumb-item active update']")).getText();
System.out.println("Text String is : "+ text);
}
#Test (priority = 101)
public void PasteText() throws IOException {
driver.findElement(By.xpath("//input[#id=\"exampleInputEmail1\"]")).sendKeys(text);
}
#AfterTest
public void afterTest() {
driver.close();
}
}
It seems that your GetText() method actually is not a test method, but a utility method. It can be a part of another package, but certainly does need to have a #Test annotation. You can still call it's logic in the BeforeTest method.
Either way, if you want to use this string in multiple tests, you need a reference to it, i.e. the value_test class should have a String text field. I would also advise using a more descriptive variable name than "text".
You can still call it in the BeforeTest set up, but now you'll have where to store the fetched value.
Along the lines of:
public class values_test {
static WebDriver driver;
static String text;
#BeforeTest
public void setup() throws Exception {
driver = new HandelDriver().getDriver("CHROME");
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
driver.get("https://chercher.tech/selenium-webdriver-sample");
GetText();
}
public void GetText() throws IOException {
text = driver.findElement(By.xpath("//li[#class='breadcrumb-item active update']")).getText();
System.out.println("Text String is : "+ text);
}
#Test (priority = 101)
public void CanPasteTextInFirstEmailField() throws IOException {
driver.findElement(By.xpath("//input[#id=\"exampleInputEmail1\"]")).sendKeys(text);
}
#Test (priority = 102)
public void CanPasteTextInSecondEmailField() throws IOException {
driver.findElement(By.xpath("//input[#id=\"exampleInputEmail2\"]")).sendKeys(text);
}
PS Each test should have a clear outcome, so you unequivocally know the results of a test case. Be sure to read up on Asserts, TestNG offers loads of possibilities.
PPS The names of tests should also be more descriptive and should de really precise on what it is testing.

POM not working on multiple test of TestNG

Below are my classes of POM:
Home
package com.sec.page;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Home {
private WebDriver driver;
#FindBy(linkText = "Frequency Calculator")
WebElement frqcalc_page;
#FindBy(linkText = "Radial O-ring Selector")
WebElement radslct_page;
public Home(WebDriver driver) {
this.driver = driver;
PageFactory.initElements(driver, this);
}
public Freq_Calc clickFreqCalcPage() {
frqcalc_page.click();
return PageFactory.initElements(driver,Freq_Calc.class);
}
public Radial_Selector clickRadialSelectorPage() {
radslct_page.click();
return PageFactory.initElements(driver,Radial_Selector.class);
}
}
Freq_Calc
package com.sec.page;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
public class Freq_Calc {
private WebDriver driver;
#FindBy(linkText = "Bearing Frequencies Calculator")
WebElement BrgFreqCalc;
#FindBy(linkText = "Gearbox Calculator")
WebElement GearCalc;
#FindBy(linkText = "Overview")
WebElement overview_page;
public Freq_Calc(WebDriver driver){
this.driver=driver;
}
public Freq_Calc_BrgFreqCalc clickBrgFreqCalc(){
BrgFreqCalc.click();
return PageFactory.initElements(driver, Freq_Calc_BrgFreqCalc.class);
}
}
Radial_Selector
package com.sec.page;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.PageFactory;
import org.openqa.selenium.support.ui.Select;
public class Radial_Selector {
private WebDriver driver;
#FindBy(name = "boreDiameter")
WebElement boreDiameter;
#FindBy(name = "boreTolerance")
WebElement boreTolerance;
#FindBy(css = "input[value='Calculate']")
WebElement calculate;
public Radial_Selector(WebDriver driver){
this.driver=driver;
}
public Radial_Selector enterboreDiameter(String value) {
boreDiameter.sendKeys(value);
return PageFactory.initElements(driver, Radial_Selector.class);
}
public Radial_Selector enterboreTolerance(String value) {
boreTolerance.sendKeys(value);
return PageFactory.initElements(driver, Radial_Selector.class);
}
public Radial_Selector clickcalculate() {
calculate.click();
return PageFactory.initElements(driver, Radial_Selector.class);
}
}
TestBase
package com.sec.util;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import com.sec.page.Freq_Calc;
import com.sec.page.Home;
import com.sec.page.Radial_Selector;
public class TestBaseSEC {
protected WebDriver driver=null;
protected String baseUrl;
protected Home homePage;
protected Radial_Selector radialselector;
protected Freq_Calc freqcalc;
#BeforeTest
public void setUp() {
baseUrl = "http://10.177.2.60:8080/engcalc/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#AfterTest
public void tearDown() throws Exception {
driver.quit();
}
}
Testcase:
package com.sec.scripts;
import org.openqa.selenium.By;
import org.openqa.selenium.support.PageFactory;
import org.testng.annotations.Test;
import com.sec.page.Home;
import com.sec.util.TestBaseSEC;
public class TestCaseSEC extends TestBaseSEC{
#Test
public void Test_RadialSelector_Page() throws Exception {
homePage = PageFactory.initElements(driver, Home.class);
driver.get(baseUrl);
radialselector = homePage.clickRadialSelectorPage();
radialselector.enterboreDiameter("10");
radialselector.enterboreTolerance("12");
radialselector.clickcalculate();
driver.findElement(By.xpath("//*[#id='top-navigation']/ul/li[1]/a/span")).click();
}
#Test
public void Test_Freq_Calc_BrgFreqCalc_Page() throws Exception {
homePage = PageFactory.initElements(driver, Home.class);
freqcalc = homePage.clickFreqCalcPage();
}
}
My isssue is:
Whenn I run Testcase, The first #Test works fine. but when it goes to second #Test, where "freqcalc =homePage.clickFreqCalcPage()"is used, it tells there is no locator for Frequency Calculator, but that exist.
Also if I use "freqcalc =homePage.clickFreqCalcPage()" as last line in first #Test then it works.
So I want to understand why it does not work for second #Test.
You have to take care of a lot of things in your code as follows :
Loading the page elements even before accessing the url makes no sense. Hence first load the URL then initialize the WebElements on the Page Object.
When you initialize a Page Object get back the object in return.
driver.get(baseUrl);
Home homePage = PageFactory.initElements(driver, Home.class);
Use the returned Page Object to access it's methods.
homePage.clickRadialSelectorPage();
Avoid chaining of Page Objects i.e. initialization of another Page Object through return statement, rather initialize the required Page Object in your Test class.
//avoid
return PageFactory.initElements(driver,Radial_Selector.class);
//within Test Class
Radial_Selector radialselector = PageFactory.initElements(driver,Radial_Selector.class);
radialselector.enterboreDiameter("10");
As you are having seperate Page Objects for different pages try to define the locators e.g. xpath for the associated WebElement in the respective Page Objects only.
//avoid
driver.findElement(By.xpath("//*[#id='top-navigation']/ul/li[1]/a/span"));
As you are having seperate Page Objects for different pages try to define the Page Object Methods e.g. click() for the WebElement's in the respective Page Factory only.
//avoid
driver.findElement(By.xpath("//*[#id='top-navigation']/ul/li[1]/a/span")).click();
First #Test works fine because, though you try to initialize Home.class nothing really happens. When driver.get(baseUrl); gets executed the elements gets initialized and your #Test gets passed. But that's not the case with Second #Test. Hence Fails
The problem here is that, the URL is not launched in the second test when the page got initialized because it is missed in the second test.
Solution 1:
Please add the line driver.get(baseUrl) in your second test as given below.
#Test
public void Test_Freq_Calc_BrgFreqCalc_Page() throws Exception {
driver.get(baseUrl);
homePage = PageFactory.initElements(driver, Home.class);
freqcalc = homePage.clickFreqCalcPage();
}
Solution 2: Move the launch URL step to before Test method. Then remove it in first test as given below.
#BeforeTest
public void setUp() {
baseUrl = "http://10.177.2.60:8080/engcalc/";
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get(baseUrl);
}
then remove it in the first test as given below.
#Test
public void Test_RadialSelector_Page() throws Exception {
homePage = PageFactory.initElements(driver, Home.class);
// driver.get(baseUrl);
radialselector = homePage.clickRadialSelectorPage();
radialselector.enterboreDiameter("10");
radialselector.enterboreTolerance("12");
radialselector.clickcalculate();
driver.findElement(By.xpath("//*[#id='top-navigation']/ul/li[1]/a/span")).click();
}

Null pointer exception in Java while calling the library

Now i modified the code but still i am getting Null Pointer Exception
Below is my modified code
enter code here
package lib;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.BeforeMethod;
//#SuppressWarnings("unused")
public class Login {
WebDriver driver;
#BeforeMethod
void Initalisation()
{
System.setProperty("webdriver.ie.driver", "C:\\Eclipse\\IEDriverServer.exe");
DesiredCapabilities capability=new DesiredCapabilities();
capability.setCapability(InternetExplorerDriver.INTRODUCE_FLAKINESS_BY_IGNORING_SECURITY_DOMAINS, true);
InternetExplorerDriver driver=new InternetExplorerDriver(capability);
driver.get("http://segotn11540.rds.volvo.com/vss_connect_testr1/Login/Login.aspx");
}
public Login(String UserName,String BrandName)
{
driver.findElement(By.xpath("//input[#name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[#name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[#name='CmdLogin']")).click();
String Title=driver.getTitle();
if(!Title.contains("VSS 4.0"))
{
System.out.println(UserName+""+"does not exists");
driver.quit();
}
CheckForCancel();
}
private void CheckForCancel() {
if(!driver.findElements(By.id("Cancel")).isEmpty())
{
driver.findElement(By.id("Cancel")).click();
}
}
}
Now I will create the main Java file
Blockquote
This will initalise the login with the parameters supplied
Import Login library
public class MessageBoard {
public static void main(String[] args)
{
Login login=new Login("TYP40FI","Volvo");
}
}
What is wrong in above code
Try to initialize the driver variable as
WebDriver driver = new WebDriver();
public Login(String UserName,String BrandName)
{
//Add this line in your code as you are trying in IE
driver = new InternetExplorerDriver();
driver.findElement(By.xpath("//input[#name='UserNameInputText']")).sendKeys(UserName);
driver.findElement(By.xpath("//input[#name='Brand']")).sendKeys(BrandName);
driver.findElement(By.xpath("//input[#name='CmdLogin']")).click();
String Title=driver.getTitle();
if(!Title.contains("VSS 4.0"))
{
System.out.println(UserName+""+"does not exists");
driver.quit();
}
CheckForCancel();
}
Debug and check: Is Initalisation() being called in the beginning?
Usually #BeforeMethod is called before test starts, so where is your #Test function. (syntax could be wrong)
If you don't really care about #Test property, that means your Main function needs to call Initalisation() before calling Login(...), otherwise the driver is not set yet (aka Null)

can someone teach me how to use property file for a simple login application

can someone help me with using property file for a sample login application? this helps in achieving me for another big automation.
I have given objects in objects.propreties
in main java class how shall i proceed with?
package valuescompare;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class practice {
public static FileInputStream fis;
public static String propertyfilepath="E:\\Ashik\\wkspSelenium\\valuescompare\\src\\valuescompare\\object.properties";
public static String getProperty(String key) throws IOException, FileNotFoundException{
fis=new FileInputStream(propertyfilepath);
Properties prop=new Properties();
prop.load(fis);
return prop.getProperty(key);
}
static WebDriver driver=new FirefoxDriver();
public static void openBrowser() throws FileNotFoundException, IOException {
//public WebDriver driver;
driver.get(getProperty("url"));
//maximizes the window
driver.manage().window().maximize();
Wait(1000);
}
public static void login() throws FileNotFoundException, IOException{
driver.findElement(By.xpath(getProperty("uidxpath"))).sendKeys(getProperty("uid"));
driver.findElement(By.xpath(getProperty("pwdxpath"))).sendKeys(getProperty("pwd"));
driver.findElement(By.xpath(getProperty("submit"))).click();
Wait(5000);
}
public static void main(String[] args) throws FileNotFoundException, IOException {
// TODO Auto-generated method stub
/*practice prac=new practice();
prac.openBrowser();
prac.login(); */
openBrowser();
login();
}
public static void Wait(int time){
try {
Thread.sleep(time);
} catch (Exception e) {
// TODO: handle exception
}
}
}
Say you create a 'config.properties' named file somewhat like this :
userName=admin
password=admin
and say you are using Java as your programming language, then you have to use it in this manner:
Properties properties = new Properties();
properties.load(new FileInputStream("Config.properties"));
String uName = properties.getProperty("userName");
String pwd = properties.getProperty("password");
Now you have got the values fetched from properties file, use it wherever required.
For more info you may refer this link: http://www.mkyong.com/java/java-properties-file-examples/

Wrong test executed first in Selenium TestNG

In the below script I want to run the Test 'Login' first and then the 'CreateCompany'. But whenever I try to run the script always the control goes to the 'CreateCompany' test at first. And since the user is not already logged in the script execution fails. Please someone tell me what is wrong with the script below.
package MyPackage;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import MyPackage.PageObjects.CompanyListing;
import MyPackage.PageObjects.LoginPage;
public class SetUpCompany {
public static WebDriver driver;
public String BaseURL=LoginPage.BaseURL();
#BeforeClass
public static void setup() {
driver = new FirefoxDriver();
driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
}
//public static WebDriver driver = new FirefoxDriver();
#Test(dataProvider="UserData")
void Login(String username, String password, String usertype){
//dr.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);
if(usertype.equals("SuperAdmin")){
String LoginURL=BaseURL+"/Manage";
driver.get(LoginURL);
LoginPage.UsernameBox(driver).sendKeys(username);
LoginPage.PasswordBox(driver).sendKeys(password);
LoginPage.LoginButton(driver).click();
//System.out.println("Hello Super admin!");
}
}
#Test(dataProvider="CompanyData")
void CreateCompany(String FrstNm, String LastNm, String CmpnyNm, String Email, String Phone, String Cell, String Web){
System.out.println("I'm here");
String ManageCompanyURL=BaseURL+"/Manage/Company";
driver.get(ManageCompanyURL);
CompanyListing.AddCmpnyBtn(driver).click();
}
#DataProvider(name="UserData")
public Object[][] loginData() {
Object[][] LoginArray = DataReader.getExcelData("E:/DataBase.xls","LoginData");
return LoginArray;
}
#DataProvider(name="CompanyData")
public Object[][] CompanyInfo() {
Object[][] CompanyArray = DataReader.getExcelData("E:/DataBase.xls","CompanyInfo");
return CompanyArray;
}
#AfterClass
public static void teardown() {
driver.close();
driver.quit();
}
}
What you have is dependent tests where CreateCompany is dependent upon login test.
You should be using dependsOnMethods. Read more here
Try writing priorities in your #Test annotations in TestNG to set the execution sequence. Here's how to do it -
#Test(priority=1, dataProvider="UserData")
void Login(String username, String password, String usertype){
//Your login code
}
#Test(priority=2, dataProvider="CompanyData")
void CreateCompany(String FrstNm, String LastNm, String CmpnyNm, String Email, String Phone, String Cell, String Web){
//Your CreateCompany code
}
More info on priorities in TestNG. Hope this helps.