Automation Testing - Selenium WebDriver - Running Multiple Test Cases - selenium

I have got some problems with my automation testing.
I have nearly around 50 test cases in my Eclipse IDE. All test cases are in different classes. Also, I have got one BaseClass that contains #beforeclass and #afterclass. In #beforeclass, the browser opens, URL opens and website URL opens then it does login procedure.
Then my test cases work. All of them begin with #Test annotation.
I connect them with using TestNG suite.
Base Class:
My BaseClass.java class
MyBaseClass.java class
TestNg:
My Suite
Example of Test Case (Class):
My Example Test Case (Class)
Here is my question:
I want to use priority (like #Test (priority=1)) for these classes (test cases) for reducing the workforce. But when there is a problem with my codes; my automation test stops. I want to, it would continue besides the stop.
The second option is using TestNG. TestNG is ok but every case, the browser opens. How can I create a test like just opening one browser then run all test cases in that browser?
By the way here is my example test case for your imagine all picture:
-#beforeclass: open browser - open URL - login
#test1: go to products screen - click create a product - create a product with initial quantity - then click save button, it should be in the products screen again.
#test2: click create a product button again. - create a product without initial quantity - click save button, it should get an error. click the cancel button to continue the third #test
#test3: so on...
-#afterclass: close browser
I really appreciate for your help! Thank you!
Edit: I switched my codes as like this. Because I dont want to my automation opens a new browser over and over again. All my test cases relates with only one screen. (products) All I want is by ordering:
Initiate #BeforeSuite (open browser, URL..)
Initiate #BeforeClass(go to Products screen - because it is common screen for all cases)
Initiate #Test for Test Case 1
Initiate #AfterClass (go to Products screen again for a connection
with test case 2
Initiate #Test for Test Case 2
My Test NG class:
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >
<suite name="AllTests" verbose="10" >
<test name="prcr1.1" >
<classes>
<class name="com.example.product.prcr1dot1" />
</classes>
</test>
<test name="prcr1.2" >
<classes>
<class name="com.example.product.prcr1dot2" />
</classes>
</test>
</suite>
My Base Class:
public class BaseClass {
protected WebDriver driver;
#BeforeSuite
public void openMyexample() throws InterruptedException {
System.out.println("Initiate LoginTest Test...");
driver = utilities.DriverFactory.open("chrome");
driver.manage().window().maximize();
driver.get("https://mystage.example.com/en/public/login/?isTestAutomationLive=true");
System.out.println("example Page Has Been Opened..");
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable((By.name("email"))));
// Enter Username Section
WebElement username = driver.findElement(By.name("email"));
username.sendKeys("automationproducts4#example.com");
Thread.sleep(1000);
wait.until(ExpectedConditions.elementToBeClickable((By.name("password"))));
// Enter Password Section
WebElement password = driver.findElement(By.name("password"));
password.sendKeys("Test*01");
Thread.sleep(1000);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//form[#id='frmLogin']/button"))));
// Click Login Button
WebElement logInButton = driver.findElement(By.xpath("//form[#id='frmLogin']/button"));
logInButton.click();
// PAGE LOADER
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//span[contains(.,'×')]"))));
Thread.sleep(1000);
// Integration Message Function WebElement - Option 1: WebElement
WebElement popupCancelButton = driver.findElement(By.xpath("//span[contains(.,'×')]"));
popupCancelButton.click();
Thread.sleep(3000);
}
#BeforeClass
public void openProducts() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 20);
// From Dashboard Section to Product Section
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//a[contains(text(),'Products')]"))));
WebElement productButton = driver.findElement(By.xpath("//a[contains(text(),'Products')]"));
productButton.click();
Thread.sleep(4000);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//button[contains(.,'Create Product')]"))));
WebElement createProductButton = driver.findElement(By.xpath("//button[contains(.,'Create Product')]"));
createProductButton.click();
Thread.sleep(4000);
}
#AfterClass
public void closeProducts() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//a[contains(text(),'Products')]"))));
WebElement productButton = driver.findElement(By.xpath("//a[contains(text(),'Products')]"));
productButton.click();
Thread.sleep(4000);
}
#AfterSuite
public void closeMyexample() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 60);
Thread.sleep(4000);
// Sign Out Thread.sleep(5000);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//div[2]/i"))));
WebElement logoutScrollDownButton = driver.findElement(By.xpath("//div[2]/i"));
logoutScrollDownButton.click();
Thread.sleep(3000);
WebElement signoutButton = driver.findElement(By.xpath("//a[contains(.,'Sign Out')]"));
signoutButton.click();
// Close Browser
System.out.println("Your Test Has Been Ended Successfully.");
Thread.sleep(1000);
System.out.println("Your Test is going to Close..");
driver.quit();
}
// Sleep Function
private void sleep(long m) {
try {
Thread.sleep(m);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
My Test Case 1:
package com.example.product;
import utilities.BaseClass;
//Test Case 1: PRCR - 1.1
//Creating a new product with a unique SKU
public class prcr1dot1 extends BaseClass {
#Test
public void prcr1dot1() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable((By.name("sku"))));
String uuid = UUID.randomUUID().toString();
driver.findElement(By.name("sku")).sendKeys(uuid);
driver.findElement(By.name("name")).sendKeys(uuid);
WebElement packType = driver
.findElement(By.xpath("//kendo-dropdownlist[#id='packTypeName']//span[#class='k-input']"));
packType.click();
wait.until(ExpectedConditions.elementToBeClickable((By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))));
driver.findElement(By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))
.sendKeys(uuid);
wait.until(ExpectedConditions.elementToBeClickable((By.id("btnCreateProductPackTypeName"))));
WebElement createPackType = driver.findElement(By.id("btnCreateProductPackTypeName"));
createPackType.click();
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//button[contains(.,'SAVE')]"))));
WebElement productSaveButton = driver.findElement(By.xpath("//button[contains(.,'SAVE')]"));
productSaveButton.click();
Thread.sleep(8000);
}
}
My Test Case 2:
import utilities.BaseClass;
public class prcr1dot2 extends BaseClass {
// Test Case 2: PRCR - 1.2
// Creating a new product with the used SKU
#Test
public void prcr1dot2() throws InterruptedException {
WebDriverWait wait = new WebDriverWait(driver, 20);
wait.until(ExpectedConditions.elementToBeClickable((By.name("sku"))));
driver.findElement(By.name("sku")).sendKeys("SKU08");
String uuid = UUID.randomUUID().toString();
driver.findElement(By.name("name")).sendKeys(uuid);
WebElement packType = driver
.findElement(By.xpath("//kendo-dropdownlist[#id='packTypeName']//span[#class='k-input']"));
packType.click();
wait.until(ExpectedConditions.elementToBeClickable((By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))));
driver.findElement(By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))
.sendKeys(uuid);
wait.until(ExpectedConditions.elementToBeClickable((By.id("btnCreateProductPackTypeName"))));
WebElement createPackType = driver.findElement(By.id("btnCreateProductPackTypeName"));
createPackType.click();
JavascriptExecutor jsx = (JavascriptExecutor) driver;
jsx.executeScript("window.scrollBy(0,450)", "");
WebElement productSaveButton = driver.findElement(By.xpath("//button[contains(.,'SAVE')]"));
productSaveButton.click();
Thread.sleep(5000);
wait.until(ExpectedConditions.elementToBeClickable((By.xpath("//button[contains(.,'Create Product')]"))));
WebElement createProductButton2 = driver.findElement(By.xpath("//button[contains(.,'Create Product')]"));
createProductButton2.click();
wait.until(ExpectedConditions.elementToBeClickable((By.name("sku"))));
driver.findElement(By.name("sku")).sendKeys("SKU08");
String uuid2 = UUID.randomUUID().toString();
driver.findElement(By.name("name")).sendKeys(uuid2);
WebElement packType2 = driver
.findElement(By.xpath("//kendo-dropdownlist[#id='packTypeName']//span[#class='k-input']"));
packType2.click();
wait.until(ExpectedConditions.elementToBeClickable((By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))));
String uuid3 = UUID.randomUUID().toString();
driver.findElement(By.xpath(
"/html//platform-root/kendo-popup[#class='k-animation-container k-animation-container-shown']//input"))
.sendKeys(uuid3);
wait.until(ExpectedConditions.elementToBeClickable((By.id("btnCreateProductPackTypeName"))));
WebElement createPackType2 = driver.findElement(By.id("btnCreateProductPackTypeName"));
createPackType2.click();
/*
* WebElement productSaveButton2 =
* driver.findElement(By.xpath("//button[contains(.,'SAVE')]"));
* productSaveButton2.click(); Thread.sleep(5000); WebElement
* productCancelButton2 =
* driver.findElement(By.xpath("//button[contains(.,'CANCEL')]"));
* productCancelButton2.click(); Thread.sleep(2000);
* wait.until(ExpectedConditions.elementToBeClickable((By.xpath(
* "//button[contains(.,'YES')]")))); WebElement productCancelYesButton =
* driver.findElement(By.xpath("//button[contains(.,'YES')]"));
* productCancelYesButton.click();
*/
}
}

I am not sure it will solve your problem or not. But This idea works for me. Using this way you can run all the test case on same browser without opening multiple times.
Here I have three class
test1.java
test2.java
test2.java
And Mainclass.java
Here is test1.java
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
public class test1 {
#BeforeClass
public void before(){
}
#Test
public static void test(WebDriver driver){
driver.get("https://www.google.com");
}
#AfterMethod
public void after(){
}
}
Here is test2.java
package test;
import org.openqa.selenium.WebDriver;
import org.testng.annotations.Test;
public class test2 {
#Test
public static void test(WebDriver driver){
driver.get("https://www.yahoo.com");
}
}
Here is mainclass.java file where I passed driver session to the test
package test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Mainclass {
public static void main(String[]args){
WebDriver driver;
driver=new ChromeDriver();
test1.test(driver);
test2.test(driver);
}
}
Now you need to run mainclass from testing.xml file.
From the main class you can open browser one time and passed driver to your all the test case so it will use browser window to run the test case.
I am not sure any other ideal idea is available or not but it will surely work for you

Related

The button in date picker is getting clicked more than the number of clicks needed [duplicate]

I am trying to select a "Depart date" as of 31st october 2018 from the calender https://spicejet.com/ But I am getting error "unknown error: Element is not clickable at point (832, 242). Other element would receive the click: ..." Please help me out. Here is my code getting such exception:
public class bookflight extends Thread {
UtilityMethods utilObj= new UtilityMethods();
#Test
public void SighnUp() throws IOException
{
utilObj.getdriver().get("https://spicejet.com");
utilObj.getdriver().manage().window().maximize();
utilObj.getdriver().findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
utilObj.getdriver().findElement(By.xpath("//a[contains(text(),'Guwahati (GAU)')]")).click();
utilObj.getdriver().findElement(By.xpath("//a[contains(text(),'Goa (GOI)')]")).click();
utilObj.getdriver().findElement(By.className("ui-datepicker-trigger")).click();
utilObj.getdriver().findElement(By.xpath("//div[#class='ui-datepicker-group ui-datepicker-group-first'])/parent:://table[#class='ui-datepicker-calendar']following-sibling::./a/contains(text(),'31')")).click();
}
}
To select From (e.g. Guwahati(GAU)), To (e.g. Goa(GOI)) destination and DEPART DATE as 31/10 within the url https://spicejet.com/ you need to induce WebDriverWait for the desired element to be clickable and you can use the following solution:
Code Block:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class spicejet_login {
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver", "C:\\Utility\\BrowserDrivers\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://spicejet.com");
new WebDriverWait(driver, 20).until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//input[#id='ctl00_mainContent_ddl_originStation1_CTXT']"))).click();
driver.findElement(By.xpath("//div[#id='glsctl00_mainContent_ddl_originStation1_CTNR']//table[#id='citydropdown']//li/a[#value='GAU']")).click();
driver.findElement(By.xpath("//div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//table[#id='citydropdown']//li/a[#value='GOI']")).click();
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.xpath("//table[#class='ui-datepicker-calendar']//tr//a[contains(#class,'ui-state-default') and contains(.,'31')]"))).click();
}
}
Browser Snapshot:
There is lots of different factors which results into this exception,
i like to suggest you to try putting some wait.
WebDriverWait wait = new WebDriverWait(utilObj.getdriver(), 10);
wait.until(ExpectedConditions.elementToBeClickable(By.id("ctl00_mainContent_ddl_originStation1_CTXT")));
then try clicking element,
utilObj.getdriver().findElement(By.id("ctl00_mainContent_ddl_originStation1_CTXT")).click();
You can click on element by Action class, based on Exception type:
Actions action = new Actions(driver);
action.moveToElement(WebElement to click).click().perform();
Updated answer to click next date.
//div[contains(#class, 'ui-datepicker-group-first')]//td[#data-month='9' and #data-year='2018']/a[.=31]
You can modify the above XPATH to select date based on YEAR/MONTH/DATE. for more XPath creation go-through my answers.
var path ="//div[contains(#class, 'ui-datepicker-group-first')]//td[#data-month='9' and #data-year='2018']/a[.=31]";
var elem = document.evaluate(path, window.document, null, 9, null ).singleNodeValue;
console.log( elem );
elem.click();
When you enter FROM and TO data, then DEPART DATE field get auto selected. So, just you need to select the first data using javascript.
FROM « //div[#id='ctl00_mainContent_ddl_originStation1_CTNR']//a[#text='Guwahati (GAU)']
TO « //div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[#text='Goa (GOI)']
DEPART DATE «
//div[contains(#class, 'ui-datepicker-group-first')]//a[contains(#class, 'ui-state-active')]
sample test program.
import io.github.yash777.driver.Browser;
import io.github.yash777.driver.Drivers;
import io.github.yash777.driver.WebDriverException;
public class SpiceJET {
static WebDriver driver;
static WebDriverWait explicitWait;
public static void main(String[] args) throws WebDriverException, IOException {
test();
}
public static void test() throws WebDriverException, IOException {
Drivers drivers = new Drivers();
String driverPath = drivers.getDriverPath(Browser.CHROME, 63, "");
System.setProperty(ChromeDriverService.CHROME_DRIVER_EXE_PROPERTY, driverPath);
DesiredCapabilities capabilities = DesiredCapabilities.chrome();
driver = new ChromeDriver( capabilities );
explicitWait = new WebDriverWait(driver, 10);
//Maximize browser window
driver.manage().window().maximize();
//Go to URL which you want to navigate
driver.get("https://spicejet.com/");
clickElement("//input[#id='ctl00_mainContent_ddl_originStation1_CTXT'][1]");
clickElement("//div[#id='ctl00_mainContent_ddl_originStation1_CTNR']//a[#text='Guwahati (GAU)']");
clickElement("//input[#id='ctl00_mainContent_ddl_destinationStation1_CTXT'][1]");
clickElement("//div[#id='ctl00_mainContent_ddl_destinationStation1_CTNR']//a[#text='Goa (GOI)']");
clickUsingJavaScript("//div[contains(#class, 'ui-datepicker-group-first')]//a[contains(#class, 'ui-state-active')]");
}
}
public static void clickElement(String locator) {
By findBy = By.xpath( locator );
WebElement element = explicitWait.until(ExpectedConditions.elementToBeClickable( findBy ));
element.click();
}
public static void clickUsingJavaScript( String locator ) {
StringBuffer click = new StringBuffer();
click.append("var elem = document.evaluate(\""+locator+"\", window.document, null, 9, null ).singleNodeValue;");
click.append("elem.click();");
System.out.println("JavaScript Click.");
jse.executeScript( click.toString() );
}
For Automatic management of Selenium Driver Executable’s in run-time for Java use SeleniumWebDrivers
NOTE: If you are selecting DEPART DATE which got auto selected then selenium throws exception
Exception in thread "main" org.openqa.selenium.WebDriverException: unknown error:
Element <input type="text" readonly="readonly" id="ctl00_mainContent_view_date2" class="custom_date_pic required home-date-pick">
is not clickable at point (784, 241). Other element would receive the click: <span class="ui-datepicker-month">...</span>
I hope below code is helpful and handle departure and return date
public class SpicejetDropdowns1 {
public static void main(String[] args) throws InterruptedException
{ System.setProperty("webdriver.chrome.driver","E:\\ChromeDriver\\ChromeDriver2.46\\chromedriver.exe");
WebDriver driver=new ChromeDriver();
driver.get("http://www.spicejet.com/");
driver.manage().window().maximize();
System.out.println(driver.getTitle()); driver.findElement(By.cssSelector("#ctl00_mainContent_rbtnl_Trip_1")).click();
// OriginStation
driver.findElement(By.xpath(".//*[#id='ctl00_mainContent_ddl_originStation1_CTXT']")).click();
driver.findElement(By.cssSelector("a[value='DEL']")).click();
// Destination
driver.findElement(By.xpath(".//*[#id='ctl00_mainContent_ddl_destinationStation1_CTXT']")).click();
driver.findElement(By.xpath("(//a[#value='HYD'])[2]")).click();
Thread.sleep(3000); driver.findElement(By.xpath("//input[#id='ctl00_mainContent_view_date1']")).click();
if(driver.findElement(By.id("Div1")).getAttribute("style").contains("1"))
{
System.out.println("its enabled");
Assert.assertTrue(true);
}
else
{
Assert.assertTrue(false);
}
while(!driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText().contains("October"))
{
// driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click();
driver.findElement(By.xpath("//a[#class='ui-datepicker-next ui-corner-all']/span[#class='ui-icon ui-icon-circle-triangle-e']")).click();
System.out.println(driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText());
}
List<WebElement> dates= driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td"));
int count= dates.size();
for(int i=0; i<count; i++)
{
String txt = driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).getText();
if(txt.equalsIgnoreCase("28"))
{
driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).click();
System.out.println(txt);
break;
}
}
// Return Date Selection
Thread.sleep(3000); driver.findElement(By.xpath("//input[#id='ctl00_mainContent_view_date2']")).click();
while(!driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText().contains("October"))
{
// driver.findElement(By.xpath("//span[contains(text(),'Next')]")).click();
driver.findElement(By.xpath("//a[#class='ui-datepicker-next ui-corner-all']/span[#class='ui-icon ui-icon-circle-triangle-e']")).click();
System.out.println(driver.findElement(By.cssSelector("div[class='ui-datepicker-title'] [class='ui-datepicker-month']")).getText());
}
List<WebElement> MDates= driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td"));
int Mcount= dates.size();
for(int i=0; i<Mcount; i++)
{
String txt = driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).getText();
if(txt.equalsIgnoreCase("31"))
{
driver.findElements(By.xpath("//table[#class='ui-datepicker-calendar']//tr//td")).get(i).click();
System.out.println(txt);
break;
}
}
//Select Passengers
Thread.sleep(4000);
driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).click();
Thread.sleep(4000);
WebElement Adults = driver.findElement(By.xpath("//select[#id='ctl00_mainContent_ddl_Adult']")); Select adultsdrp = new Select(Adults);
adultsdrp.selectByValue("2");
WebElement childs = driver.findElement(By.xpath("//select[#id='ctl00_mainContent_ddl_Child']"));
Select childsdrp = new Select(childs);
childsdrp.selectByValue("2");
driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).click();
System.out.println(driver.findElement(By.xpath(".//*[#id='divpaxinfo']")).getText());
//Static Currency Dropdown
WebElement Currency = driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency"));
Select currencydrp = new Select(Currency);
currencydrp.selectByValue("USD"); Assert.assertEquals(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")).getAttribute("value"), "USD"); System.out.println(driver.findElement(By.id("ctl00_mainContent_DropDownListCurrency")).getAttribute("value"));
}
}

I cannot select from city in MakeMyTrip wesite with Selenium WebDriver

I cannot select from city in MakeMyTrip wesbite with Selenium WebDriver. It does not select the specified city. It should click on the specified city and display the city in the "from city" field.
Here is my code:
import java.util.List;
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.Select;
public class Makemytrip {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.makemytrip.com/");
String actualTitle=" ";
actualTitle=driver.getTitle();
String url=driver.getCurrentUrl();
System.out.println(url);
String expectedTitle=actualTitle;
if(actualTitle.contentEquals(expectedTitle)){
System.out.println("Test pass");
}
else{
System.out.println("Test fail");
}
WebElement roundtrip=driver.findElement(By.xpath(".//label[#class='label_text flight-trip-type']"));
roundtrip.click();
System.out.println("Select one way option");
//driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.xpath(".//div/section/div/div/input[#id='hp-widget__sfrom']")).click();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
List<WebElement> dd_menu=driver.findElements(By.xpath(".//ul[#id='ui-id-1']/li/div/p/span"));
for(int i=0;i<dd_menu.size();i++){
WebElement element=dd_menu.get(i);
String innerhtml=element.getAttribute("innerHTML");
if(innerhtml.contentEquals("Hyderabad, India HYD" )){
element.click();
break;
}
System.out.println("Values in list " +innerhtml);
}
}
}
Input field is kind of autosuggestive dropdown here...you should use sendKeys here...one more thing use explicit wait here...I've used Thread.sleep() here...you can use WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("someid"))); Modify your code with following snippet..e.g.
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "D:\\Selenium\\chromedriver_win32\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.get("https://www.makemytrip.com/");
String actualTitle=" ";
actualTitle=driver.getTitle();
String url=driver.getCurrentUrl();
System.out.println(url);
String expectedTitle=actualTitle;
if(actualTitle.contentEquals(expectedTitle)){
System.out.println("Test pass");
}
else{
System.out.println("Test fail");
}
WebElement roundtrip=driver.findElement(By.xpath(".//label[#class='label_text flight-trip-type']"));
roundtrip.click();
System.out.println("Select one way option");
WebElement we = driver.findElement(By.xpath(".//div/section/div/div/input[#id='hp-widget__sfrom']"));
we.clear();
Thread.sleep(3000);
we.sendKeys("hyde");
Thread.sleep(3000);
we.sendKeys(Keys.RETURN);
}
I was facing the same issue during testing. Whenever you try to open "makemytrip.com" site.
Click here to check whether you are getting the same window
Because of this menu, it block the entire WebElement to get access. To resolve this problem, follow the steps given below: -
Press Ctrl+Shift+i
Click on Inspect Pointer from the left top window of inspect tools.
Drag the pointer on window screen.
Select and copy the selected tagName's Xpath available on the inspect tool.
Here is the image of intermediate help for new learner
Paste it on your respective working IDE as shown below. Here is the working code to resolved the issue
Hope this will help you.
Please use the below code to solve the issue.
String driverPath = "C:\\geckodriver.exe";
System.setProperty("webdriver.gecko.driver", driverPath);
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("https://www.makemytrip.com/flights/");
Thread.sleep(2000);
Actions act = new Actions(driver);
WebElement ele= driver.findElement(By.xpath("//label[#for=\"fromCity\"]"));
act.doubleClick(ele).perform();

Stale Element reference error on finding the element -> when navigates back to previous page

My WebDriver script is simply finding elements on the page 1(Product display page) and clicking on 1st element to see if its working, then navigates back to Product display page.
It throws Stale Element Reference error and does not click the second element on the page, says element is not attached to the page.
Code is :
public class EcommerceSearchResult {
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow
= driver.findElements
(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count);
for(int i = 0 ; i<count ; i++)
{
List<WebElement> listingelementinloop = driver.findElements(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
System.out.println(gridrow.get(i).getText());
listingelementinloop.get(i).click();
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}
}
In the loop you need to replace following line:
System.out.println(gridrow.get(i).getText());
With
System.out.println(listingelementinloop.get(i).getText());
As, elements in the gridrow list will become stale once you click on 'Back' button of browser.
Alternatively, following is another way of performing the same task:
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow
= driver.findElements
(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count);
for(int i = 1 ; i<=count ; i++)
{
WebElement element =
driver.findElement(By.xpath(".//*[#id='grid_view_products_page_container']/div/div[" + i + "]"));
System.out.println(element.getText());
element.click();
driver.navigate().back();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
}
}
Let me know, if you have any further queries.
The problem is that you are looping through a collection of elements that you collected from the page. Once you leave that page or reload it, the element references you were storing become stale, thus the error. One way to get around this is to use an index into the collection and loop over that. I've rewritten your code to make use of functions to take care of repeated actions. I've tested this code and it works.
Part of main
driver.get("http://store.demoqa.com/");
Search("iphone");
for (int i = 0; i < GetProductCount(); i++)
{
ClickProduct(i);
driver.navigate().back();
}
and supporting functions
public void Search(String searchTerm)
{
driver.findElement(By.cssSelector("input[value='Search Products']")).sendKeys(searchTerm + "\n");
}
public void ClickProduct(int index)
{
driver.findElements(By.cssSelector("h2 > a")).get(index).click();
}
public int GetProductCount()
{
return driver.findElements(By.cssSelector("h2 > a")).size();
}
Below is the solution code for your problem.Tested it in my machine and attached console screenshot.
import java.util.List;
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 EcommerceSearchResult {
public static WebDriver driver ;
public static void main(String[] args) throws InterruptedException {
System.setProperty("webdriver.chrome.driver", "C:\\chromedriver_win32\\chromedriver.exe");
driver = new ChromeDriver();
driver.manage().window().maximize();
driver.get("http://store.demoqa.com/");
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement searchBox = driver.findElement(By.xpath("//input[contains(#class,'search')]"));
searchBox.sendKeys("iphone"+"\n");
List<WebElement> gridrow = driver.findElements(By.xpath(".//*[#id='grid_view_products_page_container']/div/div"));
int count = gridrow.size();
System.out.print(count+"\n");
for(int i = 0 ; i<count ; i++)
{
WebElement listingelementinloop = driver.findElement(By.xpath(".//*[#id='grid_view_products_page_container']/div/div["+(i+1)+"]"));
System.out.println(listingelementinloop.getText());
listingelementinloop.findElement(By.xpath(".//div/a")).click();
wait.until(ExpectedConditions.urlContains("products-page/product-category"));
driver.navigate().back();
wait.until(ExpectedConditions.titleIs("iphone | Search Results | ONLINE STORE"));
}
}
}

Selenium xpath getting changed during run time

Scenario - Valid login to www.homeshop18.com and then from the Digital Menu select "Samsung".
The results are displayed and now I need to choose another brand - Micromax from the Brand section (displayed at the left side of the page)
which requires scrolling and selecting Micromax.
Issue:
Though the xpath of Micromax is correct which is //*[#id='filter_1Option_12']//div[#class='ez-checkbox'] but I see during run time of the script - some other brand is getting selected instead of micromax.
Kindly advise.
//Class for valid login to www.homeshop18.com
public class HomeShop_Login_Test
{
#FindBy(xpath="//a[#id='signInHeaderLink']") WebElement SignIn_Link;
#FindBy(xpath=".//input[#id='emailId']") WebElement Email;
#FindBy(xpath=".//input[#id='existing_user_radio']") WebElement Existing_User_Radio;
#FindBy(xpath=".//input[#id='new_user_radio']") WebElement New_User_Radio;
#FindBy(xpath=".//input[#id='password']") WebElement Password;
#FindBy(xpath=".//a[#id='signin']") WebElement SignIn_Button;
#FindBy(xpath="//a[#title='Close']") WebElement Close_Home;
public void Login_Valid()
{
WebDriverWait wait = new WebDriverWait(driver, 30);
WebElement SignIn_Link = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//a[#id='signInHeaderLink']")));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click()", SignIn_Link);
Email.sendKeys("xxx#gmail.com");
boolean selected;
selected = New_User_Radio.isSelected();
if(selected)
{
Existing_User_Radio.click();
}
Password.sendKeys("xxx");
SignIn_Button.click();
}
//Class to choose Samsung from Digital menu
public class Browse_Samsung_Mobile
{
#FindBy(xpath="//*[#id='CategoryMenu1']//a[text()='Digital']") WebElement Digital_Menu;
#FindBy(xpath="//*[#id='CategoryMenu1']//a[#title='Samsung']") WebElement Samsung_SubMenu;
#FindBy(xpath="//*[#id='filter_1Option_19']//span[#class='selected_filter_img']") WebElement Micromax;
public void Browse_Samsung()
{
WebDriverWait wait = new WebDriverWait(driver, 30);
Actions act = new Actions(driver);
act.moveToElement(Digital_Menu).perform();
act.click(wait.until(ExpectedConditions.visibilityOfElementLocated(By.xpath("//*[#id='CategoryMenu1']//a[#title='Samsung']")))).build().perform();
//WebElement Micromax = wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[#id='filter_1Option_12']//span[#class='selected_filter_img']")));
JavascriptExecutor js = (JavascriptExecutor)driver;
js.executeScript("arguments[0].click()", Micromax);
}
}
//class to call above two classes
public class Validate_Browse_Samsung_Mobile
{
WebDriver driver;
#Test
public void Validate_Browse()
{
driver = BrowserFactory.getBrowser("Firefox");
driver.get(DataProviderFactory.getConfig().getURL());
HomeShop_Login_Test login = PageFactory.initElements(driver, HomeShop_Login_Test.class);
login.Login_Valid();
Browse_Samsung_Mobile browse = PageFactory.initElements(driver, Browse_Samsung_Mobile.class);
browse.Browse_Samsung();
}
}
You should try with their name using title attribute as below :-
WebElement micromax = wait.until(ExpectedConditions.presenceOfElementLocated(By.cssSelector("a[title ~= "Micromax"] input")));
You should use following XPath to choose proper check-box:
//a[#title="GSM Mobile Phones - Micromax"]/div/input

TestNG: Method requires 2 parameters but 0 were supplied in the #Test annotation

I am a newbie to selenium testing.
Basically,
I have a selenium class like :
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Parameters;
import org.testng.annotations.Test;
import org.testng.annotations.Test;
import com.google.common.base.Function;
import java.awt.AWTException;
import java.awt.Robot;
import org.openqa.selenium.By;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverException;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import org.openqa.selenium.firefox.FirefoxDriver;
public class SeleniumTests {
public void commonFunction(){
System.setProperty("webdriver.chrome.driver", "C://Downloads//chromedriver_win32//chromedriver.exe");
WebDriver driver = new ChromeDriver();
Actions builder = new Actions(driver);
driver.get("http://localhost:3000");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
test1(driver,builder);
}
//The driver,builder will be used by all the below 3 test functions.
/**
* Calling the Most Visited API -- TEST1
*/
public void test1(WebDriver driver,Actions builder){
WebElement most_visited_link = driver.findElement(By.id("mostVisited"));
Thread.sleep(2000);
Action mouseOvermost_visited_link = builder.moveToElement(most_visited_link).build();
mouseOvermost_visited_link.perform();
Thread.sleep(2000);
driver.findElement(By.id("mostVisited")).click();
Thread.sleep(1000);
WebElement most_Visited_button = driver.findElement(By.id("datePicked"));
Action mouse_most_VisitedOverDatePicker = builder.moveToElement(most_Visited_button).build();
mouse_most_VisitedOverDatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
test2(driver,builder);
}
/**
* Calling the Status Pie API -- TEST2
* #param builder
* #param driver
*/
public void test2(WebDriver driver,Actions builder){
WebElement status_pie_link = driver.findElement(By.id("statusPie"));
Thread.sleep(2000);
//Actions builder = new Actions(driver);
Action mouseOverStatusPie = builder.moveToElement(status_pie_link).build();
mouseOverStatusPie.perform();
Thread.sleep(1000);
driver.findElement(By.id("statusPie")).click();
Thread.sleep(1000);
WebElement status_pie_button = driver.findElement(By.id("datePicked"));
Action mouseOver_Status_pie_DatePicker = builder.moveToElement(status_pie_button).build();
mouseOver_Status_pie_DatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
test3(driver,builder);
}
/**
* Calling the Old Data API -- TEST3
*/
public void test2(WebDriver driver,Actions builder){
WebElement old_data_link = driver.findElement(By.id("oldData"));
Thread.sleep(2000);
// Actions builder = new Actions(driver);
Action mouseOverOldData = builder.moveToElement(old_data_link).build();
mouseOverOldData.perform();
Thread.sleep(2000);
driver.findElement(By.id("oldData")).click();
Thread.sleep(1000);
WebElement old_data_button = driver.findElement(By.id("datePicked"));
Action mouseOverDatePicker = builder.moveToElement(old_data_button).build();
mouseOverDatePicker.perform();
Thread.sleep(2000);
driver.findElement(By.id("datePicked")).click();
Thread.sleep(2000);
driver.findElement(By.linkText("6")).click();
Thread.sleep(5000);
driver.quit();
}
}
The code executes as expected on the browser and closes the chrome window.
However, in the index report, I see log as :
3 methods, 2 skipped, 1 passed
Skipped methods :
mostVisitedfunction
statuspiefunction
Passed methods :
createConnection
Any idea where am I going wrong ?
Thanks in advance.
The method mostVisitedfunction should not have annotation because it is the helping method for yoyr test case. Instead create a new class, create a object of the same in the #test class and then call that method..
See the below example..
My test is
//MAximize the Screen
driver.manage().window().maximize();
//Go to Gmail Login Page
SignInPage SignInPage = WebUtils.GoToSignInPage(driver);
//Sign in to Login page -Send Username
SignInPage.SendkeysMethodForSignInPAge(driver, By.cssSelector("input[id='Email']") , "kishanpatelllll.8#gmail.com" );
//Click on Next
SignInPage.ClickToLogin(driver, By.cssSelector("input[id='next']"));
//Wait for password field to be visible
SignInPage.WaitForElementTobeVisible(driver, By.cssSelector("input[id='Passwd'][type='password']"));
So when i call the method SendkeysMethodForSignInPAge i wont write it in #Test.
See SendkeysMethodForSignInPAge method:
public class SignInPage {
public void SendkeysMethodForSignInPAge(WebDriver driver, By by, String s) {
WebUtils.Sendkeys(driver,by,s);
}
I created a new class and there i defined it.
This is basic flow.
Hope you can relate this.
Reply to me, if your are still stuck.
Happy Learning :-)
The error comes because if you have parameters in your #Test annotated method, then those need to come from #Parameters or #DataProvider. Else, if none of the annotation supplies the arguments, which is your case, then the error is thrown.
Apart from that what #Kishan has suggested in terms of structure of code is correct. You need to differentiate between your tests and common functions.
#Test
public void assertBackToLogin(WebDriver driver) throws InterruptedException {
LoginPage login = new LoginPage (driver);
login.assertLogin();
}
Is NOT working
Remove all the parameters and run
#Test
public void assertBackToLogin() throws InterruptedException {
LoginPage login = new LoginPage (driver);
login.assertLogin();
}