Selenium Automation : Getting Error In Explicit Method - selenium

import java.time.Duration;
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.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Syncrnization {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.setProperty("webdriver.chrome.driver", "C:\\\\chromedriver_win32 (2)\\\\chromedriver_win32 (3)\\\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(20,TimeUnit.SECONDS);
driver.manage().window().maximize();
driver.get("https://compelapps.in/eFacilito_Control_Center/Login");
WebElement username = driver.findElement(By.id("txtUserName"));
WebElement password = driver.findElement(By.id("txtPassword"));
sendKeys(driver , username , 10 , "mansoor.a");
}
public static void sendKeys(WebDriver driver , WebElement element , int timeout , String value )
{
new WebDriverWait(driver , timeout).
until(ExpectedConditions.visibilityOf(element));
element.sendKeys(value);
}
}
code Showing The Error To Change timeout Into Duration
new WebDriverWait(driver , timeout). : In This Line
If I Am Doing So ..
It Gives Error In
sendKeys(driver , username , 10 , "mansoor.a"); : In This Line In SendKey ..

You cannot use the time out in WebDriverWait like, for ex.,
new WebDriverWait(driver, 10)
Instead, you have to mention like below:
new WebDriverWait(driver, Duration.ofSeconds(10))
For implicit wait also, you have to mention like:
driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(20));

Related

Can you tell me how can i execute last three lines in selenium?

In this program I need to write a script to automate the Ecommerce site.
Main activity which is need to automate is like...
1 get URL "this is successfully executed"
2 add item to cart "this is successfully executed"
3 click on cart icon and proceed to checkout. "this is unsuccessfully executed"
for 3 point, my code is not performed. I don't know why?. I think my script is write but placement is wrong. Pls help me to find it. Thanks
package siteTesting;
import java.util.Arrays;
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.firefox.FirefoxDriver;
public class ItemsAddtoCart {
public static void main(String[] args) {
String[] itemNeeded = {"Brocolli","Cauliflower","Cucumber"};
System.setProperty("webdriver.gecko.driver", "D:\\Software\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> products = driver.findElements(By.className("product-name"));
int noOfProduct = products.size();
System.out.println(noOfProduct);
int i;
for(i=0; i<=noOfProduct; i++)
{
String[] NameofProduct = products.get(i).getText().split("-");
String uNameofProduct = NameofProduct[0].trim();
List itemNeededList = Arrays.asList(itemNeeded);
if(itemNeededList .contains(uNameofProduct))
{
System.out.println(uNameofProduct);
driver.findElements(By.xpath("//div[#class='product-action']")).get(i).click();
}
}
'these following lines are not executing, can you tell me why?'
driver.findElement(By.xpath("//a[#class='cart-icon']/img")).click();
driver.findElement(By.xpath("//button[contains(text(),'PROCEED TO CHECKOUT']")).click();
driver.findElement(By.className("promoCode")).sendKeys("rahulshettyacademy");
}
}
Please check below solution with WebDriverWait :
WebDriverWait wait = new WebDriverWait (driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#class='cart-icon']//img[contains(#class,'')]"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'PROCEED TO CHECKOUT')]"))).click();
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#placeholder='Enter promo code']"))).sendKeys("PramoCode");
Note: please add below imports:
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.By;
import org.openqa.selenium.support.ui.WebDriverWait;
Working solution
driver.get("https://rahulshettyacademy.com/seleniumPractise/#/");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
List<WebElement> products = driver.findElements(By.className("product-name"));
int noOfProduct = products.size();
System.out.println(noOfProduct);
int i;
for(i=0; i<=itemNeeded.length; i++)
{
String[] NameofProduct = products.get(i).getText().split("-");
String uNameofProduct = NameofProduct[0].trim();
List itemNeededList = Arrays.asList(itemNeeded);
if(itemNeededList .contains(uNameofProduct))
{
System.out.println(uNameofProduct);
driver.findElements(By.xpath("//div[#class='product-action']")).get(i).click();
}
}
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//a[#class='cart-icon']//img[contains(#class,'')]"))).click();
wait.until(ExpectedConditions.elementToBeClickable(By.xpath("//button[contains(text(),'PROCEED TO CHECKOUT')]"))).click();
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//input[#placeholder='Enter promo code']"))).sendKeys("PramoCode");
Output:

for loop to send assert result to excel using jxl

i am trying to write selenium script which writes pass/fail based on assert.
the problem i am facing here is the assert results are not getting inserted into excel properly. There is some issue with the for loop which i have written. please help me in fixing it.
thanks in advance.
This is the code which i have written
package DDT;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Map;
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import org.testng.asserts.SoftAssert;
import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;
import jxl.write.Label;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
public class TestPass extends ExeclUtility
{
WebDriver driver;
Map<String,Object[]> Exp;
#BeforeClass
public void openBrowser()//opening of the browser is done only 1s before executing the test data
{
System.setProperty("webdriver.chrome.driver","C:\\Users\\DELL\\Desktop\\shree\\qsp_java_selenium\\selenium\\selenium_web_driver\\chrome_driver\\chromedriver.exe");
driver=new ChromeDriver();
driver.get("file:///C:/Users/DELL/Desktop/USN%20and%20Sem.html");
}
#Test(dataProvider="TestData")
public void datasend(String username,String phnum,String Exp) throws InterruptedException, RowsExceededException, WriteException
{
WebElement name=driver.findElement(By.id("field1"));
name.clear();
name.sendKeys(username);
WebElement pwd=driver.findElement(By.id("field2"));
pwd.clear();
pwd.sendKeys(phnum);
WebElement but=driver.findElement(By.id("field4"));
but.click();
Alert alert=driver.switchTo().alert();
SoftAssert assertion=new SoftAssert();
for(int i=0;i<6;i++){
try
{
assertion.assertEquals(Exp, alert.getText());// compares the expected result in excel v/s the actual o/p
Testcase="pass";
Label l3=new Label(3,i,Testcase);
writablesh.addCell(l3);
}
catch(Exception e)
{
Testcase="fail";
Label l3=new Label(3,i,Testcase);
writablesh.addCell(l3);
}}
assertion.assertEquals(Exp, alert.getText());
alert.accept();
assertion.assertAll();
Thread.sleep(3000);
}
#AfterClass
public void closeBrowser()//browser is closed 1s after all the test data are executed
{
driver.quit();
}
#DataProvider(name = "TestData")
public Object[][] ExcelData() throws BiffException, IOException
{
String Filepath="D:\\selenium_pgms\\intern_practice\\Book1.xls";
FileInputStream Excelfile=new FileInputStream(Filepath);
Workbook Exbook=Workbook.getWorkbook(Excelfile);
Sheet Exsheet=Exbook.getSheet("Sheet1");
int Rows=Exsheet.getRows();
int Columns=Exsheet.getColumns();
String Testdata[][]= new String[Rows-1][Columns];
int count=0;
for(int i=1;i<Rows;i++)
{
for(int j=0;j<Columns;j++)
{
Cell Excell = Exsheet.getCell(j,i);
Testdata[count][j]=Excell.getContents();
}
count++;
}
Excelfile.close();
return Testdata;
}
}

Need to select "Male" from the dropdown in gmail account creation page using selenium webdriver (I want to use SelectbyIndex method)

I tried below two codes. Both didn't select the "Male" option. Could anyone please let me know where I'm doing a mistake.
It's very difficult to post the code in this site. So many conditions
My code:
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class webelements2 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\rpremala003\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ltmpl=default");
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.click();
Select dropdown = new Select (driver.findElement(By.xpath(".//*[#id='Gender']/div")));
dropdown.selectByIndex(1);
}
}
Even I used sendkeys method. But it didn't work for me
import org.openqa.selenium.Alert;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.Select;
import org.openqa.selenium.support.ui.WebDriverWait;
public class webelements2 {
public static void main(String[] args) throws InterruptedException
{
System.setProperty("webdriver.gecko.driver","C:\\Users\\rpremala003\\Downloads\\geckodriver-v0.14.0-win64\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ltmpl=default");
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.sendKeys("Male");
google.click();
}
Please suggest me how to overcome this problem
You can use Select() with <select>, <option> elements only. In this current case you can simply click() on drop-down and then click() to choose required option:
WebElement google = driver.findElement(By.xpath(".//*[#id='Gender']/div"));
google.click();
WebElement option = (driver.findElement(By.xpath("//div[text()='Male']"));
option.click();
You might also need to wait until option to be clickable:
WebDriverWait wait = new WebDriverWait(driver, 10);
WebElement option = wait.until(elementToBeClickable(By.xpath("//div[text()='Male']")));
option.click();
Simply use this and let me know if it works for you:
For Female
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":e")).click();
For Male
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":f")).click();
For Other
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":g")).click();
For Rather not say
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":h")).click();
And if you need for sign-up gmail, I tried Once:
driver.manage().window().maximize();
driver.get("https://accounts.google.com/SignUp?service=mail&continue=https%3A%2F%2Fmail.google.com%2Fmail%2F&ltmpl=default");
driver.findElement(By.xpath(".//*[#id='FirstName']")).sendKeys("Name");
driver.findElement(By.xpath(".//*[#id='LastName']")).sendKeys("Last name");
driver.findElement(By.xpath(".//*[#id='GmailAddress']")).sendKeys("Email id");
driver.findElement(By.xpath(".//*[#id='Passwd']")).sendKeys("Password");
driver.findElement(By.xpath(".//*[#id='PasswdAgain']")).sendKeys("Password Again");
//Input the month
List<WebElement> month_dropdown = driver.findElements(By.xpath(".//*[#id='BirthMonth']/div"));
//iterate the list and get the expected month
Thread.sleep(3000);
for (WebElement month_ele:month_dropdown){
String expected_month = month_ele.getAttribute("innerHTML");
// Break the loop if match found
Thread.sleep(3000);
if(expected_month.equalsIgnoreCase("August")){
month_ele.click();
break;
}
driver.findElement(By.id("BirthMonth")).click();
driver.findElement(By.id(":3")).click();
driver.findElement(By.xpath(".//*[#id='BirthDay']")).sendKeys("14");
driver.findElement(By.xpath(".//*[#id='BirthYear']")).sendKeys("1988");
driver.findElement(By.id("Gender")).click();
driver.findElement(By.id(":e")).click();
driver.findElement(By.xpath(".//*[#id='RecoveryPhoneNumber']")).sendKeys("4694222863");
driver.findElement(By.xpath(".//*[#id='RecoveryEmailAddress']")).sendKeys("recovery email id");
driver.findElement(By.id("submitbutton")).click();
Thread.sleep(3000L);

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

Import Test data from Excel sheet into selenium java code

Below is the code to create a FB account. I have excel sheet with Test data to create them. How to import that data into the below code???
Code:
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.By;
public class Facebookup {
public static void main (String args[]) throws InterruptedException
{
WebDriver gm = new FirefoxDriver();
gm.manage().window().maximize();
gm.get("https://www.facebook.com/");
gm.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
gm.findElement(By.xpath(".//*[#id='u_0_1']")).sendKeys("Tester");
gm.findElement(By.xpath(".//*[#id='u_0_3']")).sendKeys("Dravid");
gm.findElement(By.xpath(".//*[#id='u_0_5']")).sendKeys("testprod2000#gmail.com");
gm.findElement(By.xpath(".//*[#id='u_0_8']")).sendKeys("testprod2000#gmail.com");
gm.findElement(By.xpath(".//*[#id='u_0_a']")).sendKeys("Naren1234");
gm.findElement(By.xpath(".//*[#id='month']")).click();
Thread.sleep(2000);
gm.findElement(By.xpath(".//option[#value = '1']")).click();
gm.findElement(By.xpath(".//*[#id='day']")).click();
Thread.sleep(2000);
gm.findElement(By.xpath(".//option[#value = '8']")).click();
gm.findElement(By.xpath(".//*[#id='year']")).click();
Thread.sleep(2000);
gm.findElement(By.xpath(".//option[#value = '1991']")).click();
Thread.sleep(2000);
gm.findElement(By.xpath(".//*[#id='u_0_e']")).click();
gm.findElement(By.xpath(".//*[#id='u_0_i']")).click();
}
}
You can use JXL Java library which has a method to read data from excel sheets.
The jar can be downloaded from http://www.java2s.com/Code/Jar/j/Downloadjxljar.htm