Video: Document to Install and Write Script for Auto IT: AutoItDocument Code to Call Auto It Script from Java:…
Video Link:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
/* * Author: Akash Tyagi * Date: 22Sep2018 */ public class MultiWindow { public static void main(String[] args) throws InterruptedException { System.setProperty("webdriver.chrome.driver", "D:\\VisionITWorkspace\\dependencies\\chromedriver_win32\\chromedriver.exe"); //1 Create Driver object WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); //Navigate and click on the link driver.get("https://www.w3schools.com/jsref/met_win_alert.asp"); WebElement lnk_try_it_urself = driver.findElement(By.partialLinkText("Try it Yourself")); //this link will open new tab because of its implementation of <a target= "_blank"> lnk_try_it_urself.click(); //Get windows handles ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles()); //Two handle will be returned System.out.println(tabs.size()); //Switch to 2nd tab driver.switchTo().window(tabs.get(1)); //perform a click operation on the 2nd tab to check the switch is completed WebElement btn_save = driver.findElement(By.xpath("//a[@title = 'Save']")); btn_save.click(); Thread.sleep(5000); //This will close only the current tab. //This is a basic difference between driver.quit and driver.close //driver close will only close the current window or tab //where as driver quit will quit all the windows open under the driver driver.close(); //Return to default window driver.switchTo().window(tabs.get(0)); //driver quit //driver.quit(); //will close all the windows } } |
Static Block static block (also called static clause) which can be used for static initializations of a class. This code inside…
Properties File Usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
//To create own page object repository. file_name : config.properties #########@ Global properties @######## browser= chrome url= http://parabank.parasoft.com username=john password=demo ###########Login object############# user_name = username password_name = password Login_btn =//input[@type='submit'] ################################### //write a code using properties file to login para_bank application. package com.SeleniumTest; import java.io.FileInputStream; import java.io.IOException; import java.util.Properties; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.firefox.FirefoxDriver; import org.openqa.selenium.ie.InternetExplorerDriver; import org.openqa.selenium.safari.SafariDriver; // Read properties File: public class ReadClass { public static void main(String[] args) throws IOException { WebDriver driver = null; //step1: how to read properties file: Properties prop = new Properties(); //step2 :create file I/p class: and load file path. FileInputStream ip = new FileInputStream("E:/NewJavaProject/SeleniumPractice/SeleniumPractice/config.properties"); //step3: load this file I/p class reference loaded. prop.load(ip); //step4: access browser.(establish connection) System.out.println(prop.getProperty("browser")); String browserName = prop.getProperty("browser"); if(browserName.equals("chrome")){ System.setProperty("webdriver.chrome.driver","C:\\selenium\\chromedriver.exe"); driver = new ChromeDriver(); } else if(browserName.equals("FF")){ driver = new FirefoxDriver(); } else if(browserName.equals("safari")){ driver = new SafariDriver(); } else if(browserName.equals("IE")){ driver = new InternetExplorerDriver(); } else { System.out.println("no browser value is given"); } driver.get(prop.getProperty("url")); driver.findElement(By.name(prop.getProperty("user_name"))).sendKeys(prop.getProperty("username")); driver.findElement(By.name(prop.getProperty("password_name"))).sendKeys(prop.getProperty("password")); driver.findElement(By.xpath("//input[@type='submit']")).click(); } } |
Read data using excel file data driven approach using TestNG (Data Provider). Reading Login details from External Excel file using…
Types of Java Constructor and its usage
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
/** * */ package defaultConstructorCallAfterCreatingMultiOBJ; /** * @author Kushal Thadani * */ public class DefaultConstructor { int id; int ids; int count; String emp_name ; String designation; float salary; DefaultConstructor(){ ids =1012; } DefaultConstructor(int id){ this.id =1; } DefaultConstructor(int count , String emp_name){ this.id =10; this.emp_name = "Kushal Thadani"; } DefaultConstructor(int count , String emp_name , float salary){ this.id =10; this.emp_name = "Kushal Thadani"; this.salary = 1200000.00f; } DefaultConstructor(int count, String emp_name ,float salary , String designation){ this.count = count; this.emp_name =emp_name; this.salary = salary; this.designation = designation; } void m() { System.out.println(ids); } void m1() { System.out.println(id + "\t" +emp_name + "\t" + salary); } void m3() { System.out.println(count + "\t" + emp_name + "\t" + salary + "\t" +designation); } public static void main(String[] args) { DefaultConstructor t = new DefaultConstructor(); DefaultConstructor t1 = new DefaultConstructor(10 , "Parameter Constructor" , 1200000.00f); DefaultConstructor t2 = new DefaultConstructor(112 , "Kushal Thadani" , 102300.54f , "Developer"); DefaultConstructor t3 = new DefaultConstructor(1123 , "Rahul Shah" , 50400.90f , "Designer"); t.m(); t1.m1(); t2.m3(); t3.m3(); } } |
Test Case File:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
public class TC_Login{ @Test public void t_01_validate_login() { WebDriver driver = WebDriverManager.InitializeBrowser("chrome", "http://parabank.parasoft.com/parabank/index.htm"); String expected_url = "http://parabank.parasoft.com/parabank/index.htm"; //Create Page Factory object for Login page PO_Login PO_Login = PageFactory.initElements(driver, PO_Login.class); PO_AccountOverview PO_AccountOverview = PageFactory.initElements(driver, PO_AccountOverview.class); PO_Login.SetUserNameTextBox("john"); PO_Login.SetPasswordTextBox("demo"); PO_Login.ClickLoginButton(); //Create Page Factory object for Account Overview PO_AccountOverview.ValidateAccountOverviewTableIsDisplayed(); /* List<WebElement> collection = driver.findElements(By.xpath("//input[@type='text']")); int total = collection.size(); for(int i=0;i<total;i++) { collection.get(i).clear(); } */ }//end method |
Page Object Class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
package po; import org.openqa.selenium.NoSuchElementException; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.support.FindBy; import org.openqa.selenium.support.How; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import reusables.GenericReusables; public class PO_Login { //Step1 : Define the driver WebDriver driver; //Step 2: Paramatrize the constructor public PO_Login(WebDriver driver1) { this.driver = driver1; } //Step 3: Declare the Locators // Two ways to declare Locators @FindBy(how=How.NAME,using="username") WebElement txtbx_username; @FindBy(how=How.NAME,using="password") WebElement txtbx_password; @FindBy(how=How.XPATH,using="//input[@type='submit']") WebElement btn_login; /* @FindBy(id = "dsf") WebElement sdfds; */ //Set user name public void SetUserNameTextBox(String username) { try { WebDriverWait wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.visibilityOf(txtbx_username)); txtbx_username.sendKeys(username); GenericReusables.WriteLogs("info", "User Name set with text: " + username); }catch(NoSuchElementException e) { GenericReusables.WriteLogs("fail", "User Name not set with text: " + username + " due to exception " + e.toString()); e.printStackTrace(); } } //Set user name public void SetPasswordTextBox(String password) { try { WebDriverWait wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.visibilityOf(txtbx_password)); txtbx_password.sendKeys(password); GenericReusables.WriteLogs("info", "Password set with text: " + txtbx_password); }catch(NoSuchElementException e) { GenericReusables.WriteLogs("fail", "Password not set with text: " + password + " due to exception " + e.toString()); e.printStackTrace(); } }//end Method //Set user name public void ClickLoginButton() { try { WebDriverWait wait = new WebDriverWait(driver, 20); wait.until(ExpectedConditions.visibilityOf(txtbx_password)); btn_login.click(); GenericReusables.WriteLogs("info", "Clicked on Login Button"); }catch(NoSuchElementException e) { GenericReusables.WriteLogs("fail", "Unable to click on login button" + " due to exception " + e.toString()); e.printStackTrace(); } }//end Method }//end class |
Need to Automate below Scenarios: * Test cases in this Pack. * TC 1: Validate account table is displayed *…
This code is a Sample code to describe how tests can be created using Junit and best way to structure…
Handling of Frame and Frame-Set Selenium Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
WebDriver driver = new ChromeDriver(); driver.get("file:///C:/Automation/FrameProblem/FrameProblem.html"); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); //Switching to 2nd Parent Frame driver.switchTo().frame(1); //Switching to frame inside frameset driver.switchTo().frame(0); //or //WebElement o_frameset = driver.findElement(By.tagName("frameset")); //WebElement o_frameset_frame = o_frameset.findElement(By.tagName("frame")); //driver.switchTo().frame(o_frameset_frame); WebElement obj = driver.findElement(By.tagName("input")); obj.sendKeys("Akash"); |
HTML which Above Code Handles:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
<!DOCTYPE html> <html> <body> <h1>The Cascaded Frames Problem</h1> <div> <iframe src="./Frame1.html"> <!DOCTYPE html> <html> <body> <h3>Frame 1</h3> </body> </html> </iframe> <iframe src="./Frame2.html"> <!DOCTYPE html> <html> <frameset cols="25%,50%,25%"> <frame src ="./frame3.html"> <html> <body> <input type="text"></input> </body> </html> </frame> </frameset> </html> </iframe> </div> </body> </html> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
package sampletests; 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; public class MyFirstTest { public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "D:\\VisionITWorkspace\\dependencies\\chromedriver_win32\\chromedriver.exe"); //1 Create Driver object WebDriver driver = new ChromeDriver(); //Navigate driver.get("http://parabank.parasoft.com"); //Locators for Login WebElement txt_username = driver.findElement(By.xpath("//input[@name='username' and @class='input']")); WebElement txt_password = driver.findElement(By.xpath("//input[@name='password' and @class='input']")); WebElement btn_submit = driver.findElement(By.xpath("//input[@value='Log In' and @type='submit']")); //Operation on- Login in to application txt_username.sendKeys("john"); txt_password.sendKeys("demo"); btn_submit.click(); //Click on update contact info WebElement link_update_contact_info = driver.findElement(By.linkText("Update Contact Info")); link_update_contact_info.click(); //Locators for all the fields from Contact Info //WebElement txtbx_firstname = driver.findElement(By.id("customer.firstName")); // WebElement txtbx_lastname = driver.findElement(By.id("customer.lastName")); //WebElement txtbx_add_street = driver.findElement(By.id("customer.address.street")); //WebElement txtbx_add_city = driver.findElement(By.id("customer.address.city")); //WebElement txtbx_add_state = driver.findElement(By.id("customer.address.state")); //WebElement txtbx_add_zip_code = driver.findElement(By.id("customer.address.zipCode")); //WebElement txtbx_phn_number = driver.findElement(By.id("customer.phoneNumber")); //System.out.println(txtbx_firstname.getAttribute("value")); //Find Elements List<WebElement> txtbx_collection = driver.findElements(By.xpath("//input[@type='text']")); String[] arr_input = {"Akash","Tyagi","add1","add2","add3","add4","976983939"}; for(int i=0;i<txtbx_collection.size();i++) { txtbx_collection.get(i).clear(); txtbx_collection.get(i).sendKeys(arr_input[i]); } WebElement sendpayment = driver.findElement(By.xpath("//input[@value='Update Profile']")); /* txtbx_collection.get(0).sendKeys("Akash"); txtbx_collection.get(1).sendKeys("Tyagi"); txtbx_collection.get(2).sendKeys("add1"); */ } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 |
/* * Author: Akash Tyagi * Date:28Dec2017 * Detail: To explain use of Interface and Inheritance * in developing Core Selenium FW component in java for UI Operations * */ package _test; import org.openqa.selenium.WebElement; //Method List for all the Sync operations interface IUISync { //Default Method default public boolean waitForElementToAppear(WebElement element, int TimeOut){ return true; } //Default Method default public boolean waitForElementAttributeToAppear(WebElement element, String AttName, String ExpAttValue, int TimeOut){ return true; } //Default Method default public boolean waitForPageToLoad(int TimeOut){ return true; } //Default Method default public boolean waitForPageUrlToChange(String old_url, int TimeOut){ return true; } }//end Interface interface IUIEventsGeneric extends IUISync { //Default Methods in Generic UI events Interface default public String getText(WebElement element){ return element.getText(); } default public String getAttribute(WebElement element, String att_name){ return element.getAttribute(att_name); } }//end interface //Method List for all the Link Specific Operations interface IUIEventsLink { public void click(); }//end interface //Method List for all the Text Box Specific Operations interface IUIEventsTextBox{ public void sendKeys(String text); }//end interface //Method List for all the table specific operations interface IUIEventsTable { public String getTableContent(); public int getRowWithCellText(String s_text); }//end interface //UIMethods Class implements all the UI methods class UIMethods implements IUIEventsGeneric,IUIEventsLink,IUIEventsTextBox,IUIEventsTable,IUISync{ WebElement element; public UIMethods(WebElement obj){ this.element = obj; } public void click(){ waitForElementToAppear(element,10); element.click(); } public void sendKeys(String text){ element.sendKeys(text); } public String getTableContent(){ return getText(element); // Direct use of Default method from IUIEventsGeneric } public int getRowWithCellText(String s_text){ return 0; } }//End Class |
1 2 3 4 5 6 7 8 |
int a = -9; a = -a; System.out.println(a); //This will print 9 int b = 9; b = -b; System.out.println(b); //This will print -9 |
Check this Link for More: StackOverFlowQuestion
To Demonstrate use of Interfaces and Inheritance in Selenium FW
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 |
/* * Author:Akash Tyagi * Detail: To Demonstrate Use of Interfaces and Inheritance in Selenium FW * */ namespace selenium_root { //Interface with all the Possible Events interface IUIEvents { void click(IWebElement obj); void sendKeys(IWebElement obj, string textToBeSet); void selectList(IWebElement obj); string getText(IWebElement obj); void getAttributeValue(IWebElement obj); void rightMouseClick(IWebElement obj, int iX, int iY); void moveMouse(IWebElement obj, int iX, int iY); void dragAndDrop(IWebElement obj, int iX, int iY); } //UIEvents Class contains all the all the event based methods //Implements Interface: IUIEvents class UIEvents : IUIEvents { public void click(IWebElement obj) { /*Definition Yet to be Written*/} public void sendKeys(IWebElement obj, string textToBeSet) { /*Definition Yet to be Written*/} public void selectList(IWebElement obj) { /*Definition Yet to be Written*/} public string getText(IWebElement obj) { /*Definition Yet to be Written*/ return ""; } public void getAttributeValue(IWebElement obj) { /*Definition Yet to be Written*/} public void rightMouseClick(IWebElement obj, int iX, int iY) { /*Definition Yet to be Written*/} public void moveMouse(IWebElement obj, int iX, int iY) { /*Definition Yet to be Written*/} public void dragAndDrop(IWebElement obj, int iX, int iY) { /*Definition Yet to be Written*/} } //Nested Class with Parent Class as UIControls containing all the Control Based Methods //Control Based methods implements UIEvents Classes class UIControls { class UITable : UIEvents { public string getTableText(IWebElement obj) { return getText(obj); } public void getTableCellTextInRowAndClm(IWebElement obj, int iRow, int iClm) { //code to written } public void getTableRowWithCellTextAs(IWebElement obj) { /*Definition Yet to be Written*/ } public List<IWebElement> getTableCellElementsInRowAndClm(IWebElement objTable, int iRow, int iClm) { return null; } } class UIList : UIEvents { public void selectListByValue(IWebElement obj, string sValue) { } public void selectListByIndex(IWebElement obj, string sValue) { //code to written } public string getListText(IWebElement obj) { return getText(obj); } } class UILink : UIEvents { public void clickLink(IWebElement obj) { click(obj); } }//end class class UITextBox : UIEvents { public void clickTextBox(IWebElement obj) { click(obj); } public void setValueInTextBox(IWebElement obj, string textToBeSet) { sendKeys(obj, textToBeSet); } }//end class } }//end name space |
To Get List names and Paths of all the Files inside a root folder. Below Code recursively traverse every folder…
Serialization is the process of converting an object’s state (including its references) to a sequence of bytes, as well as…
Data streams support binary I/O of primitive data type values (boolean, char, byte, short, int, long, float, and double) as…
Most of the examples we’ve seen so far use unbuffered I/O. This means each read or write request is handled…
Character streams are often “wrappers” for byte streams. The character stream uses the byte stream to perform the physical I/O,…
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
public static void main(String[] args) throws IOException { // TODO Auto-generated method stub //Byte Streams FileInputStream in=null; FileOutputStream out = null; in = new FileInputStream("C:\\temp.txt"); out = new FileOutputStream("C:\\temp1.txt"); int c; while ( (c=in.read()) != -1 ){ out.write(c); } in.close(); out.close(); } |
I/O Streams Byte Streams handle I/O of raw binary data. Character Streams handle I/O of character data, automatically handling translation…
To handle multiple tabs you have to make a switch between drivers.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles()); driver.switchTo().window(tabs.get(1)); try { Thread.sleep(5000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(driver.getTitle()); o_search.o_add_to_cart_on_product_detail.click(); // driver.close(); driver.switchTo().window(tabs.get(0)); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "/Users/akashtyagi/Documents/SeleniumFW_SVN/dependencies/chromedriver"); WebDriver driver = new ChromeDriver(); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.get("https://www.w3schools.com/html/html_tables.asp"); WebElement o_tbl_object = driver.findElement(By.id("customers")); LinkedHashMap<Integer,LinkedHashMap<Integer,String>> o_result = f_get_table_content(o_tbl_object); System.out.println(o_result.toString()); } public static LinkedHashMap<Integer,LinkedHashMap<Integer,String>> f_get_table_content(WebElement o_tbl_object){ try{ LinkedHashMap<Integer,String> o_clm_data;// = new LinkedHashMap<Integer,String>(); LinkedHashMap<Integer,LinkedHashMap<Integer,String>> tbl_map_result = new LinkedHashMap<Integer,LinkedHashMap<Integer,String>>(); List<WebElement> list_rows = o_tbl_object.findElements(By.tagName("tr")); List<WebElement> list_clms; int i_row_count = list_rows.size(); int i_clm_count;// = list_clms.size(); for(int i=0;i<i_row_count;i++){ list_clms = list_rows.get(i).findElements(By.tagName("td")); i_clm_count = list_clms.size(); o_clm_data = new LinkedHashMap<Integer,String>(); for(int j=0;j<i_clm_count;j++){ o_clm_data.put(j,list_clms.get(j).getText()); }//End Inner For tbl_map_result.put(i, o_clm_data); }//End Outer For if( (tbl_map_result.get(0).size()>0) && (tbl_map_result.size()>0) ){ System.out.println("info:HTML table fetched and returned in dual hashmap"); }else{ System.out.println("fail:Unable to fetch data from table. Row Count:" + (tbl_map_result.size()) + " Clm Count: " + (tbl_map_result.get(0).size()) ); } return tbl_map_result; }catch(Exception e){ System.out.println("fail:Unable to fetch data from Html table." + " Stack Trace: " +e.getMessage()); return null; } }//End Function |
1 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
public static void f_fluent_wait_for_webelement(WebDriver driver, WebElement element, int timoutSec, int pollingSec) { FluentWait<WebDriver> fWait = new FluentWait<WebDriver>(driver).withTimeout(timoutSec, TimeUnit.SECONDS) .pollingEvery(pollingSec, TimeUnit.SECONDS) .ignoring(NoSuchElementException.class, TimeoutException.class).ignoring(StaleElementReferenceException.class); try { fWait.until(ExpectedConditions.visibilityOf(element)); fWait.until(ExpectedConditions.elementToBeClickable(element)); System.out.println("Element found - " + element.toString().substring(70)); } catch (Exception e) { System.out.println("Element Not found - " + element.toString().substring(70)); } // return element; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 |
//Downaload and Add ref to JDBC 6.0. jar location=> // ../Microsoft JDBC Driver 6.0 for SQL Server\sqljdbc_6.0\enu\jre8\sqljdbc42.jar public static LinkedHashMap<Integer,LinkedHashMap<Integer,String>> f_get_sql_result_map(String s_query){ String s_result; String connectionUrl; String DB_LOG_SERVER_NAME = "<Server name>"; Map<String,String> map_result = new HashMap<String,String>(); LinkedHashMap<Integer,String> o_clm_data; LinkedHashMap<Integer,LinkedHashMap<Integer,String>> tbl_map_result = new LinkedHashMap<Integer,LinkedHashMap<Integer,String>>(); String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; connectionUrl = "jdbc:sqlserver://" + DB_LOG_SERVER_NAME+";" + "user=<username>;password=<password>;"; Connection conn = null; Statement stmt = null; ResultSet rs =null; try{ //STEP 2: Register JDBC driver Class.forName(JDBC_DRIVER); conn = DriverManager.getConnection(connectionUrl); stmt = conn.createStatement(); rs = stmt.executeQuery(s_query); ResultSetMetaData rsmd = rs.getMetaData(); int i_clm_count = rsmd.getColumnCount(); int i_map_row_counter=0; while(rs.next()){ o_clm_data = new LinkedHashMap<Integer,String>(); for(int i=1;i<=i_clm_count;i++){ o_clm_data.put(i-1,rs.getString(i)); }//For closed tbl_map_result.put(i_map_row_counter, o_clm_data); i_map_row_counter = i_map_row_counter + 1; }//While Closed //System.out.println("Inside f_get_sql_result_multiple_records: " + map_result_query.get("ROW_1")); if(tbl_map_result.isEmpty()) { System.out.println("warn: Recordset is Empty. i.e. no records have been returned by the query. Connection Url: " + connectionUrl + " and Query: " + s_query); }else{ System.out.println("info: Recordset has been stored in HashMap and returned. Connection Url: " + connectionUrl + " and Query: " + s_query); } return tbl_map_result; }catch(SQLException se){ //Handle errors for JDBC System.out.println("warn:SQl Exception: " + se.toString() + " Query used: " + s_query); //se.printStackTrace(); return tbl_map_result; }catch(Exception e){ //Handle errors for Class.forName //e.printStackTrace(); System.out.println("warn:Other General Exception: " + e.getMessage() + " Query used: " + s_query); return tbl_map_result; }finally{ //finally block used to close resources try{ if(stmt!=null) rs.close(); conn.close(); }catch(SQLException se){ System.out.println("warn:Unable to close connection f_get_sql_result_multiple_records: " + se.getMessage()); }// do nothing try{ if(conn!=null) rs.close(); conn.close(); }catch(SQLException se){ //se.printStackTrace(); System.out.println("warn:Unable to close the Connection f_get_sql_result_multiple_records" + se.getMessage() + " Query used: " + s_query); }//end finally try }//end try }//End of Function |
1 2 3 4 5 6 7 8 9 |
public static String f_generate_random_numeric_string(long i_min, long i_max){ Random rand = new Random(); long random = (int )(Math.random() * i_max + i_min); String result = Long.toString(random); System.out.println("info", "Random numeric string generated. Min and Max mentioned as: " + i_min + " max : " + i_max + " result: " + result); return result; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
public static String f_generate_time_based_unique_integer(){ String result; String y,mon,d,h,min,s,mil; Calendar now = Calendar.getInstance(); int year = now.get(Calendar.YEAR); int month = now.get(Calendar.MONTH) + 1; // Note: zero based! int day = now.get(Calendar.DAY_OF_MONTH); int hour = now.get(Calendar.HOUR_OF_DAY); int minute = now.get(Calendar.MINUTE); int second = now.get(Calendar.SECOND); int millis = now.get(Calendar.MILLISECOND); y = Integer.toString(year); mon = Integer.toString(month); d = Integer.toString(day); h = Integer.toString(hour); min = Integer.toString(minute); s = Integer.toString(second); mil = Integer.toString(millis); result = y+mon+d+h+min+s; System.out.println("info", "Unique Time based String Generated: " + result); return result; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
package com.itpa.selenium.all_about_webdriver; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; public class HandlingDemoSiteTable { public static void main(String[] args) throws InterruptedException { WebDriver driver; WebElement o_cell; System.setProperty("webdriver.chrome.driver", "E:\\_Educational\\SeleniumStuff\\SeleniumTrainingPrepStuff\\AT\\Selenium\\ChromeDriver\\chromedriver_win32\\chromedriver.exe"); driver = new ChromeDriver(); driver.get("http://www.itprofessionalacademy.in/demo_site/web_table/index.html"); Thread.sleep(10000); System.out.println("Text is"); //Get row and column count int i_row_count = driver.findElements(By.xpath("//table/tbody/tr")).size(); int i_clm_count = driver.findElements(By.xpath("//table/tbody/tr[2]/td")).size(); for(int i=2;i<=i_row_count;i++){ for(int j=1;j<=i_clm_count;j++){ o_cell = driver.findElement(By.xpath("//table/tbody/tr["+i+"]/td["+j+"]")); System.out.print(o_cell.getText() + ","); } System.out.println(""); } } } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 |
//This test is for automation of Mercury tours website. //Function are being created for each functionality //*********Steps************** //Create Java Project //Add pacakage and class //Add selenium jar file in the Build path //Define class variables driver //Set System property for Chrome Driver //Create Driver //Open Browser //Navigate //Sync //Login package auto_mercury_tours; 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.pagefactory.ByChained; import org.openqa.selenium.support.ui.Select; import org.testng.Assert; public class AutoMercuryTours { public static WebDriver driver; //Login page Objects public static WebElement o_user_name_txtbx; public static WebElement o_password_txtbx; public static WebElement o_login_btn; //Flight Details page Objects /* public static WebElement o_flightdetails_type_radio; public static WebElement o_num_pass_list; public static WebElement o_departing_from_list; public static WebElement o_departing_date_month_list; public static WebElement o_departing_date_date_list; public static WebElement o_arriving_in_list; public static WebElement o_returning_list; public static WebElement o_service_class_radio; public static WebElement o_airline_list; public static WebElement o_continue_btn; */ public static String s_pass_count; public static String s_departing_from_list; public static String s_returning_date_date_list; public static String s_departing_date_date_list; public static String s_arriving_in_list; public static String s_returning_date_month_list; public static String s_service_class_radio; public static String s_airline_list; public AutoMercuryTours() { // TODO Auto-generated constructor stub } public static void main(String args[]) throws InterruptedException{ //Setting System property. If this is not set Webdriver can not invoke Chrome //ChromeDriver exe file location is to be set in Key: webdriver.chrome.driver System.setProperty("webdriver.chrome.driver", "E:\\_Educational\\SeleniumStuff\\SeleniumTrainingPrepStuff\\AT\\Selenium\\ChromeDriver\\chromedriver_win32\\chromedriver.exe"); //Initialize chrome Driver driver = new ChromeDriver(); //Navigate to URL. below statment can also be used for the same driver.navigate().to("http://newtours.demoaut.com/"); //driver.get("http://newtours.demoaut.com/"); 'can also be used //Find Objects of Login Page o_user_name_txtbx = driver.findElement(By.name("userName")); o_password_txtbx = driver.findElement(By.name("password")); o_login_btn = driver.findElement(By.name("login")); driver.findElement(By.name("userName")); //Perform operations on Above Objects o_user_name_txtbx.sendKeys("mercury"); o_password_txtbx.sendKeys("mercury"); o_login_btn.click(); //Sync Thread.sleep(5000); //**********Checkpoint to verify that page is loaded and user is logged in********** //Check text //boolean b_result = f_verify_text() //or //Check for any Object boolean b_result = f_verify_element_exists(driver.findElement(By.xpath("//img[@src = '/images/masts/mast_flightfinder.gif']"))); if(b_result==true){ System.out.println("Login is Successfull."); }else{ System.out.println("Login Failed."); } //***************************Find All Elements of the Page******************************************* //find objects of Flight Finder Page after Login //o_flightdetails_type = driver.findElement(new ByChained(By.name("tripType"),By.tagName("input"))); //not the right way to select values in list //o_num_pass_list = driver.findElement(By.xpath("//select[@name='passCount']/option[@value='3']")); //Clicking on Radio button in Flight type. Below is other way of selecting radio group WebElement o_flightdetails_type_radio = driver.findElement(By.xpath("//input[@name='tripType' and @value='oneway']")); //Correct way of Selecting values in Select. Gives you more control Select o_num_pass_list = new Select(driver.findElement(By.name("passCount"))); Select o_departing_from_list = new Select(driver.findElement(By.name("fromPort"))); Select o_departing_date_month_list = new Select(driver.findElement(By.name("fromMonth"))); Select o_departing_date_date_list = new Select(driver.findElement(By.name("fromDay"))); Select o_arriving_in_list = new Select(driver.findElement(By.name("toPort"))); Select o_returning_date_month_list = new Select(driver.findElement(By.name("toMonth"))); Select o_returning_date_date_list = new Select(driver.findElement(By.name("toDay"))); List <WebElement> o_service_class_radio = driver.findElements(By.name("servClass")); Select o_airline_list = new Select(driver.findElement(By.name("airline"))); WebElement o_continue_btn = driver.findElement(By.name("findFlights")); //************Set Values to be entered in the webelements************************************************ s_pass_count = "2"; s_departing_from_list = "London"; s_returning_date_date_list = "5"; // representing May as value of May is 5 in html s_departing_date_date_list = "7"; s_arriving_in_list = "Portland"; s_returning_date_month_list = "10"; // representing October as value of October is 10 in html s_returning_date_date_list = "10"; s_service_class_radio = "First"; s_airline_list = "Unified Airlines"; //**************Perform operation based on the values mentioned above************************************* o_num_pass_list.selectByValue(s_pass_count); o_departing_from_list.selectByValue(s_departing_from_list); o_departing_date_month_list.selectByValue(s_returning_date_date_list); o_departing_date_date_list.selectByValue(s_departing_date_date_list); o_arriving_in_list.selectByValue(s_arriving_in_list); o_returning_date_month_list.selectByValue(s_returning_date_month_list); o_returning_date_date_list.selectByValue(s_returning_date_date_list); o_airline_list.selectByVisibleText(s_airline_list); //Select Business Class in Radio Group //Looping through all the element of the Radio Group for(int i=0;i<=o_service_class_radio.size();i++){ if (o_service_class_radio.get(i).getAttribute("value")==s_service_class_radio){ o_service_class_radio.get(i).click(); } } //Click on continue Button o_continue_btn.click(); //*** For Information purpose. Not part of the test*** //Methods which can be applied over any WebElement Control. Few are restricted to specific type of control //below Example is for Radio Group System.out.println("Is Selected ? " + o_service_class_radio.get(1).isEnabled()); System.out.println("Is Displayed ? " + o_service_class_radio.get(1).isDisplayed()); System.out.println("Is Selected ? " + o_service_class_radio.get(1).isSelected()); System.out.println("Get Attribute. Attribute Name : value. Attribute value: " + o_service_class_radio.get(1).getAttribute("value")); System.out.println("Get Css Value: " + o_service_class_radio.get(1).getCssValue("font")); System.out.println("Get Tag Name: " + o_service_class_radio.get(1).getTagName()); System.out.println("Get Text value of the control: " + o_service_class_radio.get(1).getText()); System.out.println("Get Class: " + o_service_class_radio.get(1).getClass()); System.out.println("Get Location: " + o_service_class_radio.get(1).getLocation()); System.out.println("Get Size: " + o_service_class_radio.get(1).getSize()); //Wait for Next page to appear Thread.sleep(5000); System.out.println("Test Complete"); } //Function to verify two text. Will be used as checkpoint function public boolean f_verify_text(String s_expected, String s_actual){ if (s_expected.compareToIgnoreCase(s_actual)==0){ System.out.println("Text Matching Successfull. Expected Text: " + s_expected + " and Actual Text: " + s_actual ); return true; }else{ System.out.println("Text Matching Failed. Expected Text: " + s_expected + " and Actual Text: " + s_actual ); return false; } } //Function to check the existense of the Web Element public static boolean f_verify_element_exists(WebElement o_obj){ if(o_obj!= null){ System.out.println("Element is Present"); return true; }else{ System.out.println("Element is Absent"); return false; } } } |
Sample code how to verify element for: ispresent isvisible isenable textpresent in Selenium WebDrvier using Java.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
//To check Element Present: if(driver.findElements(By.xpath("value")).size() != 0){ System.out.println("Element is Present"); }else{ System.out.println("Element is Absent"); } //Or if(driver.findElement(By.xpath("value"))!= null){ System.out.println("Element is Present"); }else{ System.out.println("Element is Absent"); } //To check Visible: if( driver.findElement(By.cssSelector("a > font")).isDisplayed()){ System.out.println("Element is Visible"); }else{ System.out.println("Element is InVisible"); } //To check Enable: if( driver.findElement(By.cssSelector("a > font")).isEnabled()){ System.out.println("Element is Enable"); }else{ System.out.println("Element is Disabled"); } //To check text present if(driver.getPageSource().contains("Text to check")){ System.out.println("Text is present"); }else{ System.out.println("Text is absent"); } |