Skip to content

writetoprabha/SeleniumJavaWorkouts

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

26 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Topics covered so far:

  • Array list
  • Hash tables
  • Hash maps
  • Reflection API
  • Commit for the above topics: https://github.com/writetoprabha/SeleniumJavaWorkouts/commit/e3fda49d5f1af777a1c3ba9925835c10c55362b2

    Different waits supported in Selenium

    Implicit Wait:

  • it is the default timeout for all the driver.findElement statements.
  • If the element is not located within the given timeout SLA, NoSuchElementFound exception will be thrown driver.manage.timeouts().implicitlyWait(20, TimeUnit.SECONDS); driver.manage.timeouts().pageLoadTimeout(20, TimeUnit.SECONDS); //=> to make selenium wait for 20 seconds for page load
    driver.manage.timeouts().setScriptTimeout(20, Timeunit.SECONDS); //=> to make selenium wait for ajax scripts to execute

    Explicitly Wait

  • To make selenium wait for an element
  • Sample Code:
  • WebDriverWait wait = new WebDriverWait(driver, 10); => takes the driver and timeout in seconds as input
    wait.until(ExpectedConditions.visibilityOf(driver.findElementBy.Id("xyz")));
  • dynamic in nature => Waits only until the visibility of the element

    Thread.sleep()

  • Static wait
  • Should not be used frequently

    HashSets to fetch different windows opened

  • Using driver.getWindowHandles() method, we can retrieve all the opened browser windows as follows:
  • Set handles = driver.getWindowHandles(); System.out.println(handles);
  • By iterating through the Set object, we can work on different windows as shown below:
  • for(String handle:handles) { driver.switchTo.window(handle); driver.get("https://www.google.com"); }

    Alerts, Frames and Mouse Actions:

    Alerts

  • When native java script alerts are displayed, we need to make the driver point to the alert window in order to perform operations/verify text displayed in the alert
  • To do so, we can use driver.switchTo().Alert() function => returns Alert object
  • driver.findElement(By.xpath("//button[contains(text(), 'Click for JS Alert')]")).click();
        //Waits until the alert is displayed. Usually alerts are immediate.
        // But it is always safe to use the explicit wait to wait until the alert is displayed.
        WebDriverWait wait = new WebDriverWait(driver, 5);
        wait.until(ExpectedConditions.alertIsPresent());
    
        /*
        After the alert is displayed, we need to make the driver point to the alert window.
        driver.switchTo() statement is used
        After performing actions on the alert, we need to point driver back to browser window. defaultContent() method is used for the same.
        */
        Alert alert = driver.switchTo().alert();
        alert.accept();
        driver.switchTo().defaultContent();
    

    Frames

  • Frames are html pages within an another HTML page
  • In order to perform operations on frames, we need to point our driver to the frame.
  • Can be done using driver.switchTo().frame(frameIndex); statement
  • Can get the number of frames present in the web page using: driver.findElements(By.tagName("frame")).size();
  • //retrieves the frame count in the web page int frameCount = driver.findElements(By.tagName("iframe")).size();
        if(frameCount > 0) {
            driver.switchTo().frame(0);
            System.out.println(driver.findElement(By.id("tinymce")).getText());
            driver.switchTo().defaultContent();
        }
    

    MouseActions

  • Sometimes we will come across draggable objects in our web applications
  • Mouse actions can be done on such objects
  • Statement for mouse actions: Actions action = new Actions(driver);
  • action.dragAndDrop(srcWebElement, destWebElement).build().perform();
  • driver.get("https://the-internet.herokuapp.com/drag_and_drop"); WebElement src = driver.findElement(By.id("column-a")); WebElement dest = driver.findElement(By.id("column-b")); Actions action = new Actions(driver); Thread.sleep(3000); action.dragAndDrop(src, dest).build().perform();

    Cookies verification

  • At times we get test cases to verify that a specific cookie is present after performing an action in the application.
  • In such cases, we can use the getCookies method of driver.manage() to iterate through the cookies and verify

    To verify that a certain cookie is present:

  • First we need to get all the cookies and assign it to a Set of type Cookie
  • Create an Iterator object on the Set object using Iterator iteratorName = setObject.iterator(); method
  • while iterator object has next element, iterate and find the cookie
  • driver.get("https://secure01b.chase.com/web/auth/dashboard"); Set cookiesSet = driver.manage().getCookies(); //returns cookies present in the driver Iterator cookies = cookiesSet.iterator(); //create the iterator object on the set object while(cookies.hasNext()) { Cookie cookie = (Cookie) cookies.next(); System.out.println(cookie.getName() + " = " + cookie.getValue()); }

    Getting the co-ordinates of an element

    int x = driver.findElement(By.xpath("//a[contains(text(), 'A/B Testing')]")).getLocation().x; int y = driver.findElement(By.xpath("//a[contains(text(), 'A/B Testing')]")).getLocation().y;

    Database validations

    Commit: https://github.com/writetoprabha/SeleniumJavaWorkouts/commit/164719c218181d95b1c10a8e49dcaf7467052579

    4 step process:

  • Step 1: Associate the Connector jar file for the database (mySql jar is associated here) and load the driver using the Class.forName method
    Statement:
    Class.forName("com.mysql.cj.jdbc.Driver");

  • Step 2: Create the connection object using Driver.getConnection method (will return connection object)
    Statement:
    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/seleniumpractice", "root", "Colb@121");

  • Step 3: Create the statement object and pass the query in statementObj.executeQuery method => Returns result set
    Statement smt = con.createStatement(); //Returns statement to execute query ResultSet rs = smt.executeQuery("select FIRSTNAME from employeeInfo");

  • Step 4: Retrieve the results from the result set
    while(rs.next()) {
    System.out.println(rs.getString("FIRSTNAME"));
    }
  • Code for Database validation:
  • Class.forName("com.mysql.cj.jdbc.Driver"); //loads the driver for our next statement
        //pass the connection string for MySql database. Returns connection object to create the statement
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/seleniumpractice", "root", "Colb@121");
    
        Statement smt = con.createStatement(); //Returns statement to execute query
    
        ResultSet rs = smt.executeQuery("select FIRSTNAME from employeeInfo");
    
        while(rs.next()) {
            System.out.println(rs.getString("FIRSTNAME"));
        }
    

    API Validations

    Commit: https://github.com/writetoprabha/APIAutomation/commit/a5dd04bb51242f8a85c7743fdb1800950faf218b

    To invoke a REST service with Java:

    1. Set the baseURI property of the RESTASSURED static class
      Example:
      RestAssured.baseURI = "http://restapi.demoqa.com/utilities/weather/city";
    2. Create the RequestSpecification object and assign it with RestAssured.Given() method.
      Example:
      RequestSpecification httpRequest = ResetAssured.Given();
    3. Create the Response object and assign it with requestSpecificationObject.request() method
      Example:
      Response response = httpRequest.Request(METHOD.GET, "/Hyderabad");
      Note: "/Hyderabad" is the parameter passed in GET request
    4. The Response of the request invoked can be accessed using the response object
      Example:
      System.out.println(response.getResponseBody());

    Notes:

  • For POST requests, we need to add the payload and header as below:
    JSONObject requestPayload = new JSONObject();
    requestPayload.put("FirstName", firstName);
    requestPayload.put("LastName", lastName);
    requestPayload.put("UserName", userName);
    requestPayload.put("Password", password);
    requestPayload.put("Email", emailId);

    httpRequest.header("Content-Type", "application/json");
    httpRequest.body(requestPayload.toJSONString());
  • API Testing using Rest Assured BDD Approach

  • Need to include the below static packages to perform simple REST API validations with BDD approach
  • import io.restassured.RestAssured.; import static org.hamcrest.Matchers.;

  • Both POST and GET methods can be invoked and validated
  • Supports both XML and JSON responses
  • Xpath can be used to verify XML responses
  • Mobile Automation using Appium:

  • Appium supports both Android and iOS automation
  • Works well for Native, Hybrid and mobile web browsers
  • Comes from selenium family
  • Softwares needed:

  • Android Studio for android mobile emulator
  • XCode for iOS mobile emulator
  • Appium Server
  • Appium Client
  • UI Automation Viewer - to identify elements in the mobile app
  • Android Studio
  • Android studio is required for creating mobile emulators
  • Need to set ANDROID_HOME environment variable
  • The UI Automation Viewer comes along with Android studio and is located under the below path
  • ~/Android/Sdk/emulator/bin
    Appium Server
  • Appium Server listens to Appium client for commands to perform on the mobile application under test
  • Appium Server is present in npm package and can be globally installed using the below command
  • npm install -g appium
  • Appium Server can be started by running the command appium in terminal
  • Appium runs on the 127.0.0.1:4723/wd/hub location
  • Appium Client
  • Appium clients are available for all the languages supported by selenium
  • Dependency for Appium Java client can be used to work on Java language
  • When creating the driver for mobile automation, we need to tell the below information
  • Operating system in which the automation needs to be carried out
  • Emulator name (DEVICE_NAME) in which the automation needs to be performed
  • Application (APP) which needs to be launched on the mobile for automation
  • All these can be done using DesiredCapabilities object in Java as follows
  •     DesiredCapabilities capabilities = new DesiredCapabilities();
    
        //To tell Appium server whether to perform the automation on Android or iOS device, specify the framework name:
        capabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "uiautomator2");
    
        //Name of the emulator in android studio
        capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Pixel_3a_XL_API_28");
    
        //To tell Appium server which app to open:
        capabilities.setCapability(MobileCapabilityType.APP, System.getProperty("user.dir") + "/apps/ApiDemos-debug.apk");
    
    
        //Driver object creation to perform the automation. Takes 2 arguments -
        AndroidDriver<AndroidElement> driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
    
  • Identification of elements displayed on the app are done using UI Automation Viewer tool
  •     driver.findElement(By.xpath("//android.widget.TextView[@text='Preference']")).click();
        driver.findElement(By.xpath("//android.widget.TextView[@text='3. Preference dependencies']")).click();
        driver.findElement(By.xpath("//android.widget.CheckBox[@resource-id='android:id/checkbox']")).click();
        driver.findElement(By.xpath("//android.widget.TextView[@text='WiFi settings']")).click();
        driver.findElement(By.xpath("//android.widget.EditText[@resource-id='android:id/edit']")).sendKeys("Some text goes here");
        driver.findElement(By.xpath("//android.widget.Button[@text='OK']")).click()
    

    Touch Action

  • Appium supports performing gestures on the app - like long press, swipe, scroll, tap etc.,
  • TouchAction class's longPress method can be used to perform long press and drag operations
  •     TouchAction touch = new TouchAction(driver);
    
        touch.longPress(LongPressOptions.longPressOptions().withElement(element(source)).withDuration(Duration.ofSeconds(2))).moveTo(element(destination)).release().perform();
    
  • The longPress statement can also be written like below
  • touch.longPress(element(source)).moveTo(element(destination)).release().perform();
  • Using UIAndroidAutomator's UiScrollable method, we can scroll to a particular element on the screen
  • driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView(text(\"Visibility\"));");

    driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector()).scrollIntoView(text("Date Widgets"));");

    About

    Selenium and java workouts

    Resources

    Stars

    Watchers

    Forks

    Releases

    No releases published

    Packages

    No packages published

    Languages