I have the following code, I am extracting data from excel sheet and filling web form. Its a registration form and its registering two users. But once the second test runs, it starts another instance of driver. May I know how to do it in one instance.
#RunWith(Parameterized.class)
public class form {
private static WebDriver driver;
private String first;
private String last;
private String phone;
private String country;
private String about;
public form(String first, String last, String phone, String country, String about)
{
this.first = first;
this.last = last;
this.phone = phone;
this.country = country;
this.about = about;
}
#Before
public void before()
{
driver = new FirefoxDriver();
driver.manage().window().maximize();
}
#Parameters
public static Collection<Object[]> supplydata() throws IOException
{
File excel = new File("C:\\Users\\Master\\Desktop\\search_query_log.xls");
FileInputStream fis = new FileInputStream(excel);
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet ws = wb.getSheet("Sheet1");
int rowNum = ws.getLastRowNum() + 1;
int colNum = ws.getRow(0).getLastCellNum();
Object[][] data = new Object[rowNum][colNum];
for (int i=0; i < rowNum ; i++)
{
HSSFRow row = ws.getRow(i);
for(int j=0; j < colNum ; j++)
{
HSSFCell cell = row.getCell((short) j);
if(cell.getCellType()==cell.CELL_TYPE_STRING)
{
data[i][j]=cell.getStringCellValue();
}
else if(cell.getCellType()==cell.CELL_TYPE_NUMERIC)
{
data[i][j]=String.valueOf(cell.getNumericCellValue());
}
}
}
return Arrays.asList(data);
}
#Test
public void testcase() throws IOException, InterruptedException
{
driver.get("http://www.samplereg.com");
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.findElement(By.id("fname")).sendKeys(first);
driver.findElement(By.name("lastname")).sendKeys(last);
driver.findElement(By.name("phonenumber")).sendKeys(phone);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
WebElement gender = driver.findElement(By.xpath("//input[#value='Male']"));
if (!gender.isSelected())
gender.click();
assertTrue(gender.isSelected());
driver.findElement(By.name("country")).sendKeys(country);
driver.findElement(By.name("desc")).sendKeys(about);
Select industry = new Select(driver.findElement(By.name("industry")));
assertFalse(industry.isMultiple());
assertEquals(6, industry.getOptions().size());
List<String> exp_options = Arrays.asList(new String[]{"Select Industry", "IT", "BPO","Sales","Development","Other"});
List<String> act_options = new ArrayList<String>();
for(WebElement option : industry.getOptions())
act_options.add(option.getText());
assertArrayEquals(exp_options.toArray(),act_options.toArray());
assertEquals("Select Industry", industry.getFirstSelectedOption().getText());
industry.selectByVisibleText("BPO");
assertEquals("BPO", industry.getFirstSelectedOption().getText());
Select education = new Select(driver.findElement(By.name("educationList")));
assertFalse(education.isMultiple());
assertEquals(4, education.getOptions().size());
List<String> exp_options1 = Arrays.asList(new String[]{"Select Education", "Post Graduate", "Graduate", "Under Graduate"});
List<String> act_options1 = new ArrayList<String>();
for(WebElement option1 : education.getOptions())
act_options1.add(option1.getText());
assertArrayEquals(exp_options1.toArray(),act_options1.toArray());
assertEquals("Select Education", education.getFirstSelectedOption().getText());
education.selectByVisibleText("Graduate");
assertEquals("Graduate", education.getFirstSelectedOption().getText());
WebElement hobby = driver.findElement(By.xpath("//input[#value='Listening Music']"));
if (!hobby.isSelected())
hobby.click();
assertTrue(hobby.isSelected());
driver.findElement(By.cssSelector("input[type=file]")).sendKeys("C:\\Users\\Master\\Desktop\\image.jpg");
driver.findElement(By.cssSelector("input[type=submit]")).click();
}
#After
public void after()
{
//driver.quit();
}
}
How about trying the below. Hope my understanding is correct.
#BeforeClass
public static void setUpClass() {
driver = new FirefoxDriver();
driver.manage().window().maximize();
Alert javascriptAlert = driver.switchTo().alert();
System.out.println(javascriptAlert.getText()); // Get text on alert box
javascriptAlert.accept(); // Chose whether to accept or cancel based on need
}
You can remove the #before method.
Related
Testcase file. Testcase with fillo query data driven
Suppose when the query (String qry="Select * from Sheet1 where ACC='M' and GEN='F'";) returns 5 data rows for one test case and i want to use the same qry for the next case but with different data row
public class Testcases {
public WebDriver driver;
Fillo fillo;
static ExtentReports report;
ExtentTest test;
//String PAGE_URL = "Your_page_Url";
#BeforeClass public static void allTestsPrep(){
report = new ExtentReports("Report.html",true);
}
#AfterClass public static void allTestCleanUp() {
report.flush();
}
#Before
public void setUp() {
String browserName = getParameter("browser");
if (browserName.equalsIgnoreCase("chrome")){
driver = new ChromeDriver();
}
else if(browserName.equalsIgnoreCase("firefox")) {
driver = new FirefoxDriver();}
else if (browserName.equalsIgnoreCase("ie")) {
driver = new InternetExplorerDriver();
}
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
driver.manage().window().maximize();
// driver.get(PAGE_URL);
}
#Test
public void Testcase001() throws FilloException, InterruptedException {
String qry="Select * from Sheet1 where ACC='M' and GEN='F'";
test = report.startTest("Testcase 1 - Test findpage");
Useragreement usragr = new Useragreement(driver);
usragr.CheckboxSelectall();
test.log(LogStatus.PASS, "VERIFIED");//report
}
#After
public void close() {
driver.close();
test = null;
}
private String getParameter(String name) {
String value = System.getProperty(name);
if (value == null)
throw new RuntimeException(name + " is not a parameter!");
if (value.isEmpty())
throw new RuntimeException(name + " is empty!");
return value;
}
}
Fillo file
Now the code will be `FILLO.inputText(Phone_Number,"Pno",qry)``;
public class FILLOAPP {
public static String getTestValue(String fieldName, String qry) throws FilloException{
String testString=xlTesting(fieldName,qry);
return testString;
}
public static String xlTesting(String fieldName, String qry) throws FilloException{
String testval=null;
Fillo fillo=new Fillo();
Connection connection=fillo.getConnection("resources/TestData.xlsx");
String sqry=qry;
Recordset recordset=connection.executeQuery(sqry);
while(recordset.next()){
ArrayList<String> dataColl=recordset.getFieldNames();
Iterator<String> dataIterator=dataColl.iterator();
while(dataIterator.hasNext()){
for (int i=0;i<=dataColl.size()-1;i++){
String data=dataIterator.next();
String dataVal=recordset.getField(data);
if (data.equalsIgnoreCase(fieldName)){
String testData=dataColl.get(i);
String testValue= recordset.getField(testData);
testval=testValue;
}
}
break;
}
}
recordset.close();
connection.close();
return testval;
}
public static void inputText(WebElement driver, String fieldName, String qry) throws FilloException{
String fval=getTestValue(fieldName, qry);
driver.sendKeys(fval);
}
}
public String dataRead(String sheetname, String testcaseid, String header) throws IOException {
String value = null;
try {
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
book = new XSSFWorkbook(fis);
sheet = book.getSheet(sheetname);
int lastRowNum = sheet.getLastRowNum();
// System.out.println(lastRowNum);
int lastCellNum = sheet.getRow(0).getLastCellNum();
// System.out.println(lastCellNum);
for (int i = 0; i < lastRowNum; i++) {
for (int j = 1; j < lastCellNum; j++) {
Map<String, Map<String, String>> excelmap = new HashMap<String, Map<String, String>>();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(sheet.getRow(0).getCell(j).toString(), sheet.getRow(i + 1).getCell(j).toString());
excelmap.put(sheet.getRow(i + 1).getCell(0).toString(), map);
if (excelmap.containsKey(testcaseid)) {
Map<String, String> w = excelmap.get(testcaseid);
if (map.containsKey(header)) {
value = w.get(header).toString();
}
}
}
}
} catch (Exception E) {
}
return value;
}
public void excelWrite(String sheetname, String testcaseid, int columnno, String value) throws Throwable {
File file = new File(TESTDATA_SHEET_PATH);
FileInputStream fis = new FileInputStream(file);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetname);
// sheetnoOfColumns = sheet.getRow(0).getPhysicalNumberOfCells();
int lastRowNum = sheet.getLastRowNum();
for (int i = 0; i < lastRowNum; i++) {
Map<Map<String, String>, String> excelmap = new HashMap<Map<String, String>, String>();
LinkedHashMap<String, String> map = new LinkedHashMap<String, String>();
map.put(sheet.getRow(0).getCell(0).toString(), sheet.getRow(i + 1).getCell(0).toString());
if (map.containsValue(testcaseid)) {
excelmap.put(map, value);
String w = map.get("TestCase ID");
Map<String, String> fin = new HashMap<String, String>();
fin.put(w, value);
XSSFRow row = sheet.getRow(i + 1);
Cell createcell = row.createCell(columnno);
createcell.setCellValue(value);
}
}
FileOutputStream fileOut = new FileOutputStream(TESTDATA_SHEET_PATH);
workbook.write(fileOut);
fis.close();
fileOut.close();
}
public Map ReadExcelExecution() throws Throwable {
LinkedHashMap<String, Object[]> map = new LinkedHashMap<String, Object[]>();
try {
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.getSheet("IssuePolicy");
int TotalRow = sheet.getLastRowNum();
int noOfColumns = (sheet.getRow(0).getPhysicalNumberOfCells() - 1);
int lastCellNum = sheet.getRow(0).getLastCellNum();
// System.out.println(TotalRow);
// System.out.println(noOfColumns);
// System.out.println(lastCellNum);
map.put("1",
new Object[] { "TestCase ID", "PolicyNo", "IssueDate", "Accumulated Value", "GMWB Type",
"MAWA/2LMAWA", "Remaining MAWA", "Protected Income Payment", "Accumulated Value DOD",
"DataComparison", "Comments" });
for (int i = 1; i <= TotalRow; i++) {
{
String testcaseid = sheet.getRow(i).getCell(0).toString();
String policyno = sheet.getRow(i).getCell(noOfColumns).toString();
String issuedate = sheet.getRow(i).getCell(2).toString();
String values = null;
map.put(testcaseid, new Object[] { testcaseid, policyno, issuedate, values, values, values, values,
values, values, values, values });
}
}
} catch (Exception E) {
}
return map;
}
public void writinginInputFile(String sheetname, Map mapvalue) throws Throwable {
// write excel file and file name is SaveTestNGResultToExcel.xls
FileInputStream fis = new FileInputStream(TESTDATA_SHEET_PATH);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet sheet = wb.createSheet(sheetname);
keyset = mapvalue.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = sheet.createRow(rownum++);
Object[] objArr = (Object[]) ReadExcelExecution().get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if (obj instanceof Date)
cell.setCellValue((Date) obj);
else if (obj instanceof Boolean)
cell.setCellValue((Boolean) obj);
else if (obj instanceof String)
cell.setCellValue((String) obj);
else if (obj instanceof Double)
cell.setCellValue((Double) obj);
}
}
try {
FileOutputStream out = new FileOutputStream(new File(TESTDATA_SHEET_PATH));
wb.write(out);
out.close();
System.out.println("Successfully saved Selenium WebDriver TestNG result to Excel File!!!");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (NullPointerException e) {
}
}
package seleniumproject;
import java.util.Set;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
public class Multiplewindowpopup {
public static void main(String[] args) {
WebDriver driver;
String Userdir = System.getProperty("user.dir");
System.setProperty("webdriver.chrome.driver",Userdir+"\\Driver\\chromedriver.exe");
driver = new ChromeDriver(); // launch chrome
driver.manage().window().maximize();
driver.manage().deleteAllCookies();
driver.get("http://www.popuptest.com/goodpopups.html");
//find ID of the 2nd link
driver.findElement(By.linkText("Good PopUp #2")).click();
Set<String> windowhandler = driver.getWindowHandles();
Iterator<String> myiterator = windowhandler.iterator();
////////////// //how to get index of parent and child window ???
//now we have two window IDs and moving the window from parent to child.
driver.switchTo().window(childWindow);
System.out.println("child window title"+driver.getTitle());
//closing the child window
driver.close();
// comming back to parentwindow
driver.switchTo().window(parentWindow);
System.out.println("parent window title"+driver.getTitle());
}
}
I want to pass username and password in a webpage from excel sheet. help me to get the out put.
error is display as red underline in getRow(), getColumn(), getCell() etc.
This is my java file:
public class NewTest_tstng_excel {
public WebDriver driver;
public static XSSFSheet excelSheet;
public void login() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
}
#BeforeClass
public void testSetup() {
driver=new FirefoxDriver();
driver.manage().window().maximize();
//wait = new WebDriverWait(driver, 5);
}
#Test(dataProvider="empLogin")
public void VerifyInvalidLogin(String userName, String password) {
driver.get("URL goes here");
driver.findElement(By.id("UserName")).sendKeys(userName);
driver.manage().timeouts().implicitlyWait(120, TimeUnit.SECONDS);
driver.findElement(By.id("Password")).sendKeys(password);
driver.findElement(By.id("btnLogin")).submit();
}
#DataProvider(name="empLogin")
public Object[][] loginData() {
Object[][] arrayObject = getExcelData("E:\\disha.shah\\myWork\\sele_proj\\FAM_Excel data\\src\\DataFile\\Book1.xlsx","Sheet1");
return arrayObject;
}
public String[][] getExcelData(String fileName, String sheetName) {
String[][] arrayExcelData = null;
try {
FileInputStream fs = new FileInputStream(fileName);
XSSFWorkbook workBook = new XSSFWorkbook(fs);
//Workbook wb = Workbook.getWorkbook(fs);
//Sheet sh = wb.getSheet(sheetName);
excelSheet = workBook.getSheet("Sheet1");
int totalNoOfCols = excelSheet.getColumns();
int totalNoOfRows = excelSheet.getRows();
arrayExcelData = new String[totalNoOfRows-1][totalNoOfCols];
for (int i= 1 ; i < totalNoOfRows; i++) {
for (int j=0; j < totalNoOfCols; j++) {
arrayExcelData[i-1][j] = excelSheet.getCell(j, i).getContents();
}
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
e.printStackTrace();
} catch (BiffException e) {
e.printStackTrace();
}
return arrayExcelData;
}
#Test
public void tearDown() {
driver.quit();
}
}
in excel: there is 2 column containing username and password.
See if getRow is null.
You can do createRow().
If in the excel you don't use the row you need, you will have to create a new row, otherwise you use getRow if the row is already in use!
I need to automate links in my website. I want to pass xpath values once in each iteration of loop. So that I can minimize my coding
public class Popup
{
private WebDriver driver;
private String baseUrl;
//private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
#Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.example.com/info.php";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
#Test
public void testPopup() throws Exception {
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a[2]/i")).click();
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a[3]/i")).click();
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a[4]/i")).click();
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a[5]/i")).click();
Can you try this?
for(int j=2; j<=5; j++) {
driver.findElement(By.xpath("//div[#id='info-list']/div[2]/div/div/div/div/a["+j+"]/i")).click();
}
Hi Sanchit Khera Try this one :
int i = 0;
//extract the link texts of each link element
for (WebElement e : linkElements)
{
linkTitles[i] = e.getText();
i++;
}
//Test each link
for (String t : linkTitles)
{
// Titles Click
driver.findElement(By.linkText(t)).click();
Searched everywhere but could not find solution how to do following:
As Example:
for (int i = 0; i < 5; i++) {
#Test
public void test1(){
assertThat(assertvalue 1);
}
#Test
public void test2(){
assertThat(assertvalue 2);
}
#Test
public void test3(){
assertThat(assertvalue 3);
}
}
Of course I can use dataProvider or invocationCount and do all asserts in one test case, but if one assert will fail whole test case fail. I want kind of separate one big test case for 3 small test cases
Any help appreciated
Having dependencies between test cases is discouraged. You could achieve a similar result--checking each value 1-5 without short-circuiting and stopping after a failure on 2--using SoftAssert.
SoftAssert soft = new SoftAssert();
soft.fail("Failure # 1\n");
soft.fail("Failure # 2");
soft.assertAll();
should output:
The following assertions failed:
Failure # 1
Failure # 2
I tried following code:
public class SimpleTest {
private String param = "";
public SimpleTest(String param) {
this.param = param;
}
#BeforeClass
public void beforeClass() {
System.out.println("Before SimpleTest class executed.");
}
#Test
public void testMethod1() {
System.out.println("testMethod parameter value is: " + param);
}
#Test(dependsOnMethods = "testMethod1")
public void testMethod2() {
System.out.println("testMethod parameter value is: " + param);
}
}
public class SimpleTestFactory{
#Factory
public Object[] factoryMethod() {
return new Object[] {
new SimpleTest("one"),
new SimpleTest("two")
};
}
And tried following code and it does not keep order
Add invocationCount
#Test(priority = 350, groups = "success" ,invocationCount = 10)
public void test1(){
assertThat(assertvalue 1);
}
Use "property",if you want to execute test1(),add "priority =1"
#Test
public void test1(priority =1){
System.out.println("execute frist");;
}
#Test
public void test2(priority =2){
assertThat(assertvalue 2);
}
#Test
public void test3(priority =3){
assertThat(assertvalue 3);
}
#Test
public void main() throws IOException,InterruptedException
{
FileInputStream fil = new FileInputStream(new File("C:\\Users\\V-DKumaravelu\\ECM Data\\ECM-Data-Sheet.xlsx"));
XSSFWorkbook workbook=new XSSFWorkbook(fil);
XSSFSheet sheet=workbook.getSheet("ECM");
int count=sheet.getLastRowNum();
System.out.println(count);
for (int i=1;i<=5;i++){
Snapshot sc = new Snapshot();
XSSFRow row = sheet.getRow(i);
XSSFCell cell = row.getCell(0);
String ServiceDate=cell.getStringCellValue();
System.out.println("DOSate is "+ ServiceDate);
XSSFCell cell1=row.getCell(1);
String MemberID=cell1.getStringCellValue();
System.out.println("Member "+MemberID);
XSSFCell cell2 = row.getCell(2);
String FacilityCode=cell2.getStringCellValue();
System.out.println("Facility Code "+FacilityCode);
XSSFCell cell3=row.getCell(3);
String ReleaseOfInfo=cell3.getStringCellValue();
System.out.println("ROI " + ReleaseOfInfo);
XSSFCell cell4 = row.getCell(4);
String ContactName=cell4.getStringCellValue();
System.out.println("Contact Name " + ContactName);
XSSFCell cell5=row.getCell(5);
String ContactPhoneAreaCode=cell5.getStringCellValue();
System.out.println("ContactPhoneAreaCode " + ContactPhoneAreaCode);
XSSFCell cell6 = row.getCell(6);
String ContactPhonePrefix=cell6.getStringCellValue();
System.out.println("ContactPhoePrefix " + ContactPhonePrefix);
XSSFCell cell7=row.getCell(7);
String ContactPhoneLine=cell7.getStringCellValue();
System.out.println("ContactPhoneLine " + ContactPhoneLine);
XSSFCell cell8=row.getCell(8);
String ContactPhoneExt=cell8.getStringCellValue();
System.out.println("ContactPhoneExt " + ContactPhoneExt);
XSSFCell cell9 = row.getCell(9);
String ServiceType=cell9.getStringCellValue();
System.out.println("ServiceType " + ServiceType);
XSSFCell cell10=row.getCell(10);
String ServiceLevel=cell10.getStringCellValue();
System.out.println("ServiceLevel " + ServiceLevel);
XSSFCell cell11=row.getCell(11);
String PRIS=cell11.getStringCellValue();
System.out.println("PRIS " + PRIS);
XSSFCell cell12 = row.getCell(12);
String DiagnosisCode=cell12.getStringCellValue();
System.out.println("Diagosis " + DiagnosisCode);
XSSFCell cell13=row.getCell(13);
String ProcedureCode=cell13.getStringCellValue();
System.out.println("Procedure Code " + ProcedureCode);
XSSFCell cell14=row.getCell(14);
String unitsProcedure=cell14.getStringCellValue();
System.out.println("Procedure Units " + unitsProcedure);
System.setProperty("webdriver.chrome.driver", "C:\\Users\\V-DKumaravelu\\eclipse-workspace\\ECM Portal\\driver\\chromedriver.exe");
ChromeDriver driver = new ChromeDriver();
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
driver.get("http://10.32.52.79:8888/ECM/clientlogin.aspx");
driver.findElement(By.id("txtUserId")).sendKeys("203861P");
driver.findElement(By.id("txtPassword")).sendKeys("RETINA01");
driver.findElement(By.id("btnLogin")).click();
driver.findElement(By.xpath("//*[#id=\'_ctl7_lbNewPA\']")).click();
driver.findElement(By.id("outpatientServices2")).click();
driver.findElement(By.id("serviceDate")).sendKeys(ServiceDate);
driver.findElement(By.id("memberID")).sendKeys(MemberID);
sc.main(driver);
driver.findElement(By.id("nextLink1")).click();
Select select = new Select(driver.findElement(By.id("facilityCode")));
select .selectByVisibleText(FacilityCode);
Select select1 = new Select(driver.findElement(By.id("releaseOfInfo")));
select1 .selectByVisibleText(ReleaseOfInfo);
driver.findElement(By.id("ContactName")).sendKeys(ContactName);
driver.findElement(By.id("ContactPhoneAreaCode")).sendKeys(ContactPhoneAreaCode);
driver.findElement(By.id("ContactPhonePrefix")).sendKeys(ContactPhonePrefix);
driver.findElement(By.id("ContactPhoneLine")).sendKeys(ContactPhoneLine);
driver.findElement(By.id("ContactPhoneExt")).sendKeys(ContactPhoneExt);
sc.main(driver);
driver.findElement(By.id("nextLink1")).click();
Select select2 = new Select(driver.findElement(By.xpath("//*[#id='serviceType']")));
select2 .selectByVisibleText(ServiceType);
Select select3 = new Select(driver.findElement(By.xpath("//*[#id=\'levelOfService\']")));
select3 .selectByVisibleText(ServiceLevel);
driver.findElement(By.id("facilityPris")).sendKeys(PRIS);
driver.findElement(By.id("diagnosisCode")).sendKeys(DiagnosisCode);
driver.findElement(By.id("addDiagnosis")).click();
driver.findElement(By.id("codeProcedure")).sendKeys(ProcedureCode);
driver.findElement(By.id("unitsProcedure")).sendKeys(unitsProcedure);
driver.findElement(By.id("addProcedure")).click();
sc.main(driver);
driver.findElement(By.id("nextLink2")).click();
driver.findElement(By.id("btnSubmit")).click();
sc.main(driver);
Assert.assertNotNull(driver.findElement(By.xpath("//*[#id=\'Table1\']/tbody/tr[5]/td[6]")),"Failed");
driver.close();
}}
}
I am beginner in Selenium, there are two separate .xls file file one for GmailTestSuite.xls and other for objectrepository.xls.
I have created MainClass, in it I have written a code which read both .xls file, also I've open the driver in it and perform operation. But problem is that it continuously open new driver but don't perform any operation.
Please suggest and let me know where I'm going wrong.
public class MainClass {
static Properties properties= null;
public static void main(String[] args) throws IOException, BiffException{
// TODO Auto-generated method stub
ReadPropertyFile readConfigFile= new ReadPropertyFile();
properties= readConfigFile.loadPropertiess();
ExcelHandler testSuite= new ExcelHandler("D:\\GmailTestSuite.xls", "Suite");
testSuite.columnData();
int rowCount= testSuite.rowCount();
System.out.println("Total Rows="+rowCount);
for(int i=1;i<rowCount;i++)
{
String executable= testSuite.readCell(testSuite.getCell("Executable"), i);
System.out.println("Executable="+executable);
if(executable.equalsIgnoreCase("y")){
// exe. the process
String scenarioName= testSuite.readCell(testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name="+scenarioName);
ExcelHandler testScenarios= new ExcelHandler("D:\\GmailTestSuite.xls", scenarioName);
int rowWorkBook1= testScenarios.rowCount();
for(int j=1; j<rowWorkBook1;j++){
String framWork= testScenarios.readCell(testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(testScenarios.getCell("Operation"), j); //SendKey
String value= testScenarios.readCell(testScenarios.getCell("Value"), j);
System.out.println("FRMName="+framWork+",Operation="+operation+",Value="+value);
ExcelHandler objectRepository= new ExcelHandler("D:\\objectrepository.xls", "OR");
objectRepository.columnData();
int rowCount1= testSuite.rowCount();
System.out.println("Total Rows="+rowCount1);
for(int k=1;k<rowCount;k++){
String frameWorkName= objectRepository.readCell(objectRepository.getCell("Executable"), k);
String ObjectName= objectRepository.readCell(testScenarios.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(testScenarios.getCell("Locator"), k); //SendKey
System.out.println("FrameWorkName="+frameWorkName+",ObjectName="+ObjectName+",Locator="+Locator);
//ExcelHandler executeOperation = new ExcelHandler(ObjectName, operation, value);
File file= new File("D:\\softs\\FF installed\\FF18\\firefox.exe");
FirefoxBinary fb = new FirefoxBinary(file);
WebDriver driver = new FirefoxDriver(fb,new FirefoxProfile());
driver.get("https://www.gmail.com");
WebElement we = driver.findElement(By.id("Email"));
if(operation.equalsIgnoreCase("SendKey"))
{
we.sendKeys("abc#gmail.com");
we.sendKeys("si#2013");
}
if(operation.equalsIgnoreCase("Click"))
we.click();
}
}
}
}
}
A couple of guide lines for better formed code:
Break your code into methods that only do one thing each. That way it's easier to manage and nicely compartmentalized, plus you don't enter into indentation hell with such embedded loop and if structures as the one you have over here.
Use class variables for things like the WebDriver instance, so you can initialize it once and keep calling on it later.
Don't hard code text into the application, use constants. Then you only need to define the text once and can refer to it multiple times. Makes the code much easier to maintain and change, when you don't have to search and replace through entire class, after some details (like a file path) change.
Also, I'm guessing you meant to do the following:
loop the rows in objectRepository in the k-loop, instead of looping the rows in the testSuite again.
get cells from objectRepository rather than from testScenarios when reading the cells from objectRepository
Example:
public class MainClass {
private static final String BROWSER_PATH = "D:\\softs\\FF installed\\FF18\\firefox.exe";
private static final String TEST_SUITE_PATH = "D:\\GmailTestSuite.xls";
private static final String OBJECT_REPOSITORY_PATH = "D:\\objectrepository.xls";
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
private static final By EMAIL_INPUT = By.id("Email");
// other constants
private WebDriver driver;
private Properties properties;
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws IOException, BiffException {
MainClass main = new MainClass();
main.handleTestSuite();
}
private void handleTestSuite() {
ReadPropertyFile readConfigFile = new ReadPropertyFile();
properties = readConfigFile.loadPropertiess();
ExcelHandler testSuite = new ExcelHandler(TEST_SUITE_PATH, "Suite");
testSuite.columnData();
int rowCount = testSuite.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int i = 1; i < rowCount; i++) {
String executable = testSuite.readCell(testSuite.getCell("Executable"), i);
System.out.println("Executable=" + executable);
if (executable.equalsIgnoreCase("y")) {
// exe. the process
String scenarioName = testSuite.readCell(testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name=" + scenarioName);
handleScenario(scenarioName);
}
}
}
private void handleScenario(String scenarioName) {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH, scenarioName);
int rowWorkBook1 = testScenarios.rowCount();
for (int j = 1; j < rowWorkBook1; j++) {
String framWork = testScenarios.readCell(testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(testScenarios.getCell("Operation"), j); // SendKey
String value = testScenarios.readCell(testScenarios.getCell("Value"), j);
System.out.println("FRMName=" + framWork + ",Operation=" + operation +
",Value=" + value);
handleObjects(operation);
}
}
private void handleObjects(String operation) {
ExcelHandler objectRepository = new ExcelHandler(OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(objectRepository.getCell("Executable"), k);
String ObjectName = objectRepository.readCell(objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkName=" + frameWorkName +
",ObjectName=" + ObjectName + ",Locator=" + Locator);
operateWebDriver(operation);
}
}
private void operateWebDriver(String operation) {
WebElement we = driver.findElement(EMAIL_INPUT);
if (operation.equalsIgnoreCase("SendKey")) {
we.sendKeys("abc#gmail.com");
we.sendKeys("si#2013");
} else if (operation.equalsIgnoreCase("Click")) {
we.click();
}
}
}
If ExcelHandler is your own implementation, you really should move the getCell(String s) method inside the readCell() method to change the call pattern of handler.readCell(handler.getCell("foo"), i) into handler.readCell("foo", i). If it's a library you're using, you can always make a helper method:
private static String readCell(ExcelHandler handler, String cellName, int row) {
return handler.readCell(handler.getCell(cellName), row);
}
EDIT
Since you're having problems with getting WebDriver to work, simplify things and take everything else out of the equation for now. In order to do that let's ignore all the reading data from .xls files. This is where having different methods for different things makes your design shine, since you can just comment one method call instead of having to comment out 50 lines of code from your one mega method.
Changed the above code a bit (just commented call to the other methods out and omitted them from the snippet, moved the line opening the correct page into constructor and rewrote the operateWebDriver() method a bit):
public class MainClass {
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
private static final By EMAIL_INPUT = By.id("Email");
private static final By PASSWORD_INPUT = By.id("Passwd");
private static final By SIGN_IN_BUTTON = By.id("signIn");
private static final String EMAIL = "test#abc.com";
private static final String PASSWORD = "test123";
private WebDriver driver;
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws IOException, BiffException {
MainClass main = new MainClass();
//main.handleTestSuite();
main.operateWebDriver("Click", EMAIL_INPUT);
main.operateWebDriver("SendKey", EMAIL_INPUT, EMAIL);
main.operateWebDriver("Click", PASSWORD_INPUT);
main.operateWebDriver("SendKey", PASSWORD_INPUT, PASSWORD);
main.operateWebDriver("Click", SIGN_IN_BUTTON);
}
private void operateWebDriver(String operation, By element) {
operateWebDriver(operation, element, null);
}
private void operateWebDriver(String operation, By element, String keys) {
WebElement we = driver.findElement(element);
if (operation.equalsIgnoreCase("SendKey")) {
we.sendKeys(keys);
} else if (operation.equalsIgnoreCase("Click")) {
we.click();
}
}
}
Then once you get WebDriver working, you can start reading the data from the files and using it to operate WebDriver.
#user2092132- You require to make changes on two places in your code
1: Insert new line after line- System.out.println("Total Rows="+rowCount);
WebDriver driver = null;
2:Change line from: WebDriver driver = new FirefoxDriver(fb,new FirefoxProfile());
To: driver = new FirefoxDriver(fb,new FirefoxProfile());
Above two changes should resolve initiating new instacne of FF each time.