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;
}
}
Related
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:
My first question here! Pardon if i am missing out anything!
I have written code to pick URL from excel and then click on elements in url by fetching corresponding data from the excel sheet. The script runs fine as expected. But it is still throwing Invalid Argument exception after the final run of loop. There are no errors (atleast to my eyes) and i have verified the url links in excel. They are fine. Script currently behaves the way i want. But still i am getting the exception. The final step of driver.close is not performed. Please check the code and let me know where i went wrong.
First column in excel is url. Following columns has text which is picked up by script and used for linktext command to click on the elements in url.
package newpackage;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.InvalidObjectException;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelRead {
public static void main(String[] args) throws Exception {
System.setProperty("webdriver.chrome.driver","C:\\driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
WebDriverWait wait=new WebDriverWait(driver, 20);
String baseUrl = "https://google.com/";
driver.get(baseUrl);
FileInputStream fis = new FileInputStream("D:\\test_data.xlsx");
#SuppressWarnings("resource")
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheetAt(0);
int s=sheet.getLastRowNum()+1;
for(int i=0; i<s; i++)
{
int k = sheet.getRow(i).getLastCellNum();
XSSFCell cell=sheet.getRow(i).getCell(0);
String url=cell.toString();
driver.get(url);
Thread.sleep(3000);
System.out.println("Launched "+url);
Thread.sleep(5000);
for(int j=1;j<k;j++)
{
String data0=sheet.getRow(i).getCell(j).getStringCellValue();
driver.findElement(By.linkText(data0)).click();
System.out.println(data0+" Saved");
}
}
driver.close();
}
}
Currently getting this after script runs execution:
Exception in thread "main" org.openqa.selenium.InvalidArgumentException: invalid argument
You can check for null as given below. so that, even though you have empty data in excel, it will work.
for(int i=0; i<s; i++)
{
int k = sheet.getRow(i).getLastCellNum();
XSSFCell cell=sheet.getRow(i).getCell(0);
String url=cell.toString();
if(url!=null && !url.isEmpty())
{
driver.get(url);
Thread.sleep(3000);
System.out.println("Launched "+url);
Thread.sleep(5000);
for(int j=1;j<k;j++)
{
String data0=sheet.getRow(i).getCell(j).getStringCellValue();
if(data0!=null && !data0.isEmpty())
driver.findElement(By.linkText(data0)).click();
System.out.println(data0+" Saved");
}
}
}
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<mpl=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<mpl=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<mpl=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);
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
Can anyone provide me a link/document with information on how to write and test custom liferay portlets with Selenium.
I am using Liferay 6.1EE
Thanks
Same as with other tests, assuming you want to run as JUnit test
package org.ood.selenium.test;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.IncorrectnessListener;
import com.gargoylesoftware.htmlunit.ScriptException;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.html.HtmlButton;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.javascript.JavaScriptErrorListener;
import com.thoughtworks.selenium.SeleneseTestBase;
import com.thoughtworks.selenium.Selenium;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebDriverBackedSelenium;
import org.apache.commons.io.FileUtils;
import org.apache.commons.logging.LogFactory;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Level;
import java.util.regex.Pattern;
public class MyTest extends SeleneseTestBase {
WebDriver driver =null;
#Before
public void setUp() throws Exception {
DesiredCapabilities dc = DesiredCapabilities.firefox();
// dc.setCapability(FirefoxDriver.BINARY, new
//File("C:/Program Files (x86)/Mozilla Firefox/firefox.exe").getAbsolutePath());
dc.setJavascriptEnabled(true);
// driver= new HtmlUnitDriver(true);//Not properly working
driver = new FirefoxDriver(dc);
String baseUrl = "http://localhost:8080/web/guest/home";
selenium = new WebDriverBackedSelenium(driver, baseUrl);
}
/* #Test
public void homePage() throws Exception {
final WebClient webClient = new WebClient();
//HTMLUNit throws lots of errors
webClient.setJavaScriptEnabled(true);
webClient.setJavaScriptErrorListener(new JavaScriptErrorListener() {
public void timeoutError(HtmlPage htmlPage, long allowedTime,
long executionTime) {
// TODO Auto-generated method stub
}
public void scriptException(HtmlPage htmlPage,
ScriptException scriptException) {
System.out.println(scriptException.getMessage());
}
public void malformedScriptURL(HtmlPage htmlPage, String url,
MalformedURLException malformedURLException) {
System.out.println(url);
}
public void loadScriptError(HtmlPage htmlPage, URL scriptUrl,
Exception exception) {
// TODO Auto-generated method stub
}
});
//webClient.setThrowExceptionOnFailingStatusCode(false);
webClient.setThrowExceptionOnScriptError(false);
final HtmlPage page = webClient.getPage("http://localhost:8080/web/guest/home");
webClient.getCache().clear();
page.getElementById("sign-in").click();
page.getElementById("_58_login").type("test#liferay.com");
page.getElementById("_58_password").type("test#liferay.com");
final HtmlButton submit = (HtmlButton)page.getByXPath("//input").get(0);
submit.click();
//assertEquals("HtmlUnit - Welcome to HtmlUnit", page.getTitleText());
System.out.println("Title= " +page.getTitleText());
final String pageAsXml = page.asXml();
// assertTrue(pageAsXml.contains("<body class=\"composite\">"));
System.out.println("pageAsXml=" +pageAsXml);
final String pageAsText = page.asText();
//assertTrue(pageAsText.contains("Support for the HTTP and HTTPS protocols"));
System.out.println("pageAsText="+pageAsText);
webClient.closeAllWindows();
}*/
#Test //Using Graphical GUI
public void testMytest() throws Exception {
//driver.get("http://localhost:8080/web/guest/home");
selenium.open("/");
//selenium.click("id=sign-in");
driver.findElement(By.id("sign-in")).click();
driver.findElement(By.name("_58_login")).clear();
driver.findElement(By.name("_58_login")).sendKeys("test#liferay.com");
driver.findElement(By.name("_58_password")).sendKeys("123");
//driver.findElement(By.name("_58_login")).sendKeys("test#nsn.com");
//driver.findElement(By.name("_58_password")).sendKeys("test");
driver.findElement(By.className("aui-button-input-submit")).submit();
//selenium.setSpeed("1000");
//selenium.waitForPageToLoad("5000");
//Select a nested div( the NodeTree)
driver.findElement(By.xpath("//div[contains(#class,'aui-tree-node-content')" +
" and (contains(.,'TreeNodeX'))]//div[contains(#class,'aui-tree-hitarea')]"))
.click();
//selenium.captureScreenshot("d:/_del/sel_screen.png");//this throws an error
//workaround
File scrFile = ((TakesScreenshot)driver).getScreenshotAs(OutputType.FILE);
FileUtils.copyFile(scrFile, new File("d:/_del/sel_screen.png"));
System.out.println("Bodytex=[" +selenium.getBodyText() +"]End Body Text");
String[] titles= selenium.getAllWindowTitles();
System.out.println("Titles Start-");
for (int i = 0; i < titles.length; i++) {
System.out.println(titles[i]);
}
System.out.println("Titles End");
verifyEquals(true, selenium.getBodyText().contains("Site View"));
}
#After
public void tearDown() throws Exception {
selenium.stop();
}
}