Sunday 23 October 2016

Handling Keyboard and Mouse Events with Selenium WebDriver


In many cases we will come across a scenario where we want to automate special type of Keyboard and Mouse events and for which Selenium Web Drover Provided Advance User Interface API with class names Actions and  Action.Handling keyboard events and mouse events in Selenium is very simple so let us start with it.

Let us see how we can use the Special Events in our Selenium Tests
Video Tutorial -


Test Scenario - Consider you want to perform mouse over action on the About Me menu as per given in below screenshot. As you observe the my site menu when you mouse over , it will change back ground color so lets see how we can test it using Selenium.



Test Case -


ackage mypackage;

import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

public class myclass {

public static void main(String[] args) {
String baseUrl = "http://www.qaautomated.com/";
       System.setProperty("webdriver.chrome.driver", 
         "C:\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();

        driver.get(baseUrl);           
        WebElement aboutMe= driver.findElement(By.id("aboout_me"));
    
        
        Actions builder = new Actions(driver);
        Action mouseOverAboutMe = builder
                .moveToElement(aboutMe)
                .build();
        
        String bColor = td_Home.getCssValue("background-color");
        System.out.println("Before Mouse hover: " + bColor );        
        mouseOverAboutMe.perform();        
        bColor = td_Home.getCssValue("background-color");
        System.out.println("After Mouse hover: " + bColor );
        driver.quit();
}
}

Most Frequently Used  Keyboard and Mouse Events APIs -

1. clickAndHold() - Clicks without releasing at the pointed mouse location.

2. contextClick() -
Performs a context-click (Right Click) at the pointed mouse location.

3. doubleClick()-
Performs a double-click at the pointed mouse location.

4. dragAndDrop(source, target) -
Performs click-and-hold at the location of the source element, moves to the location of the target element, then releases the mouse.
source- web element to emulate button down at.
target- web element to move to and release the mouse at.

5.dragAndDropBy(source, x-offset, y-offset) - Performs click-and-hold at the location of the source element, moves by a given offset, then releases the mouse.
source- web element to emulate button down at.
xOffset- offcet ofhorizontal move.
yOffset- offset o fvertical move.

6.keyDown(modifier_key) -
Does not release the modifier key - subsequent interactions may assume it's kept pressed.
modifier key  sample =Keys.ALT, Keys.SHIFT, or Keys.CONTROL etc.

7.keyUp(modifier _key) -
Releases already pressed modified key.

8.moveByOffset(x-offset, y-offset) -
Moves the mouse from its current position by the given offset.
x-offset- horizontal offset. ( negative value =  moving the mouse left)
y-offset- vertical offset(negative value = moving the mouse up)

9. moveToElement(toElement) -
Moves the mouse to the middle of the element

10.release() -Releases the pressed left mouse button at the current mouse location pointer.

11.sendKeys(onElement, charsequence) -
Sends a series of keystrokes onto the element.

Please share this with your friends and leave your feedback in comment section.

Saturday 22 October 2016

Access Web Elements inside Table with Selenium



Accessing Web Elements Inside a table using xpath is very important to learn as you will need it to write automated Selenium Test Cases.As it is very difficult for developers to provide ids for each table element hence we need to use Xpath for accessing each cell element. So this post is very useful to understand accessing table using Selenium.

Accessing Table Cell Element -

HTML Code -
 

<html>
<body>
<table id="table1">
<table>
<tr>
<td>first </td>
<td>second </td>
</tr>
<tr>
<td>third</td>
<td>four </td>
</tr>
<table>
</body>
</htmt>

Xpath Writing - Let us write xpath for clicking on cell with text "thrid"

As we know XPath locators  start with a double forward slash "//" and then followed by the parent tag name. Since we are dealing with tables, the parent element will be the <table> tag. The first part of our XPath will be "//table".

The element with tab <tbody> is under <table> means <tbody> is child tag of  of <table>. Now oue xpath will be modified as "//table/tbody".

Now inside <tbody> we need to access the second <tr> and first <td> so now xpath will be modofied as "//table/tbody.tr[2]/td[1]".

WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[1]"));  

Accessing Nested Table Cell Element -

HTML Code -


<html>
<body>
<!-- Outer Table -->
<table id="table1">
<tbody>
<tr>
<td>first </td>
<td>second </td>
</tr>
<tr>
<td>third</td>
<!-- Inner Table -->
<table id="table2">
<tbody>
<tr>
<td>first 1</td>
<td>second 2</td>
</tr>
<tr>
<td>third 3</td>
<td>four 4 </td>
</tr>
</tbody>
<table>
</tr>
</tbody>
<table>
</body>
</htmt>

Xpath Writing -

Xpath for locating "second 2"


WebElement thirdCell = driver.findElement(By.Xpath("//table/tbody/tr[2]/td[2]
                                                 +"/table/tbody/tr[1]/td[2]"));

Accessing table elment using attributes -

When the there are multiple tables in HTML code or if the tables are too much nested we can use any of the attributes provided in html code such as Id, Width, height, values etc. Refer the first html code where table id is given as table 1 then we can write xpath as per shown below 


WebElement thirdCell = driver.findElement(By.Xpath("//table[@id=\"table1\"]/tbody/tr[2]/td[1]"));  


Selenium Test to Check Links in Web Page are working

Testing all the links inside a web page is working fine or not is most important testing scenario. We can test this scenario very easily with selenium. As we know the links will be inside html tag <a> we can use By.tagName("a") locator and use an iterator in java to make the process simple.

This Simple example will help you perform various types of testing like -

1. Testing broken links on webpage using selenium.
2. Clicking on a link or click on all links on  web page to verify links are working fine.
3. Counting number of Links on web page.
4. Getting List of Links on web page.
5. Find out list of non working links on webpage.

Example -

Consider we want to test all links in homepage of www.qaautomated.com

Test Case -

Check out below test case and read the descriptions mentioned in the comment section to understand the flow.

package selenium.tests;

import java.util.List;



import java.util.concurrent.TimeUnit;
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;

public class TestAllLinks { 
 
 public static void main(String[] args) {
        String baseUrl = "http://www.qaautomated.com/";
        System.setProperty("webdriver.chrome.driver", 
         "C:\\Users\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        String notWorkingUrlTitle = "Under Construction: QAAutomated";
        driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);

        driver.get(baseUrl);
        List<WebElement> linkElements = driver.findElements(By.tagName("a"));
        String[] linkTexts = new String[linkElements.size()];
        int i = 0;

        //extract the link texts of each link element
        for (WebElement elements : linkElements) {
            linkTexts[i] = elements.getText();
            i++;
        }

        //test each link
        for (String t : linkTexts) {
            driver.findElement(By.linkText(t)).click();
            if (driver.getTitle().equals(notWorkingUrlTitle )) {
                System.out.println("\"" + t + "\""
                        + " is not working.");
            } else {
                System.out.println("\"" + t + "\""
                        + " is working.");
            }
            driver.navigate().back();
        }
        driver.quit();
    }
}

Output -

"Home" is working fine
"About Me" is working fine
"Contact Us" is not working ....

If you find this useful please share the post with your friends using share options given below. You can write your feedback and suggestion in the comment section.

Implicit Wait , Explicit Wait and Fluent Wait in Selenium



As we have all faced that we need to wait for loading in web application.This is where our selenium tests fail if  the web element test trying to interact with is not visible on the screen. In this case If the Web element is not found then it throws the exception "ElementNotVisibleException".We can solve this issue of unpredictable test case failure in Selenium using "Waits".

Video Tutorial -

 

In this post we will see 3 types of Waits which are widely used in Selenium -

1.Implicit Wait.
2.Explicit Wait
3.Fluent Wait

1. Implicit Wait - 

Implicit Wait means informing selenium web driver to wait for specific amount of time and if the web element is not visible after waiting for that specific point then throw "No such Element found Exception". 

Check out the Example given below to understand how to use Implicit wait in Selenium Test Case.In below Test case we will add a wait for 30 seconds after opening the browser so that that the page is gets loaded completely.As we implicitly specify the time and Time Unit this is called as implicit wait.
method implicitlywait() accepts 2 parameters first one is time value and second one is time unit like days,hours,minutes,seconds,milliseconds etc.

package com.selenium.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver; 
import java.util.concurrent.TimeUnit; 
 public class BrowserTests {

 public static void main(String[] args) throws Exception {
  System.setProperty("webdriver.chrome.driver", 
 "C:\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver=new ChromeDriver();
  driver.get("http://qaautomated.blogspot.in");
  driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
  driver.quit();
 }

}
 

2. Explicit Wait -

In Explicit wait along with wait time we also provide the wait condition. It will wait till the condition or the maximum wait time provided before throwing the Exception"ElementNotVisibleException".

We can say that Explicit wait is intelligent wait as it waits dynamically for specified condition. Check out the below test case example for using Selenium Explicit wait.First We need to instantiate WebDriverWait  wait object with Web Driver Reference and time frame in seconds.

Then we can use until() method for passing Expected Wait Condition and use it in our test case for waiting until the element is visible on the screen.Here we are using  visibilityofElementLocated() condition.To find out about other conditions type ExpectedConditions in eclipse IDE and press cltr+space bar and you will get the list of conditions which you can use in with Explicit Wait.

package com.selenium.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver; 
import java.util.concurrent.TimeUnit; 
 public class BrowserTests {

 public static void main(String[] args) throws Exception {
 System.setProperty("webdriver.chrome.driver", 
 "C:\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver=new ChromeDriver();
  WebDriverWait wait = new WebDriverWait(WebDriverRefrence,20);
  driver.get("http://qaautomated.blogspot.in");
  WebElement aboutMe;
aboutMe= wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("about_me")));      
aboutMe.click();
  driver.quit();
 }

}
3. Fluent Wait -

Fluent wait is when we can setup a repeat time cycle to verify the condition is met or not. Fluent wait allows use to setup frequency with a time frame to verify the given expected condition at regular time interval. This wait is used in test scenario where element loading time is variable (it can be 10,15 or 20 secs) In this case we can use frequency to handle "ElementNotVisibleException".

Check the below example we are defining the wait time as 20 seconds and then 5 seconds for frequency. This means that the to wait for 20 secs to meet the condition after each 5 seconds till the condition is met.




package com.selenium.tests;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver; 
import java.util.concurrent.TimeUnit; 
 public class BrowserTests {

 public static void main(String[] args) throws Exception {
 System.setProperty("webdriver.chrome.driver",  
"C:\\chromedriver_win32\\chromedriver.exe");
  WebDriver driver=new ChromeDriver();
  Wait<WebDriver> wait = new FluentWait<WebDriver>(driver)       
.withTimeout(20, TimeUnit.SECONDS)    
.pollingEvery(5, TimeUnit.SECONDS)    
.ignoring(NoSuchElementException.class); 
  driver.get("http://qaautomated.blogspot.in");
  WebElement aboutMe= wait.until(new Function<WebDriver, WebElement>() {       
public WebElement apply(WebDriver driver) { 
return driver.findElement(By.id("about_me"));     
 }  
});  
  
aboutMe.click(); 

  driver.quit();
 }

}

Saturday 15 October 2016

Selenium APIs to perform different Actions

In the tutorial we are going to learn one of the important thing about Selenium Web Driver without this you will not be able to start writing your Selenium Test Cases. In our Web application we have various web elements to access such as text boxes, radio buttons, check boxes, drop downs, multi-select dropdowns etc. Let us see how to access these web elements using selenium web driver + java.

1. Entering Values into Text box -
Entering value into input text box is very simple using selenium is very simple first locate the text box using its id,class name or xpath and then use sendKeys() method to enter values. The below line of code will enter "myname" string into textbox with id username.

Example - driver.findElement(By.id("username")).sendKeys("myname");

2. Deleting Value from textbox-
For clearing value from text box selenium provides clear() method.

Example - driver.findElement(By.id("username")).clear();

3. Selecting value with Radio Button -
We need to use click() method to toggle the radio button value.

Example -  driver.findElement(By.xpath("//input[text()='option1']")).click();

4. Check box select/deselect -
Like radio button check box toggling is done using click() method. In the below example first we locate the check box and then perform click action on it and then display the status as TRUE if the check box is selected and FALSE if check box is deselected.

Example - WebElemnt checkbox=driver.findElement(By.id("check_box"));
                  checkbox.click();
                 System.out.println(checkbox().isSelected);

5. Clicking on Link Text -
To click on link text click() method is used and for selected link text linkText() or partialLinkText() is used .

Example - driver.findEment(By.linkText("Click Here")).click();
                                    OR
                   river.findEment(By.partialLinkText("Here")).click();

6. Drop Down Access -
1. Import package org.openqa.selenium.support.ui.select
 import org.openqa.selenium.support.ui.select
2. Declare the drop down web element as instance of select class.
Select dropdown = new Select (driver.findElement(By.id("CityList")))
3. We can use any of the Select class methods to perform actions on the drop down
 dropdown.selectByVisibleText("Delhi");


If you find this helpful then please share with your friends and post your questions and feedback in the comments section below. Add me via google+ or follow me on facebook to get latest post updates.



 

Introduction to Selenium



 

What is Selenium?

Selenium is free open source automation testing tool for web bases applications. Selenium is very similar to QTP (Quality Test Pro) tool provided by HP but it only focuses on Web based application. Selenium comes with various handy automation testing tools like Selenium IDE, Selenium RC, Selenium Web Driver and Selenium Grid. In this post I am going to explain briefly about all those tools so that you can select a more suitable tool for you automated testing. As per latest release Selenium RC and Selenium are merged in single Suit called Selenium 2.

Video Tutorial -

 

Selenium IDE

Selenium IDE (Integrated Development Environment) is the simplest framework which is provided as add-on for firefix browser. which is used for record and play test case. So this has very limited features and if you want to write advance test cases then you must use more advance selenium frameworks like Selenium RC or Selenium Web Driver.

Pros -
1. Very Easy to use.
2. No programming language is required except HTML basics.
3. Recorded Test Cases can be used to Export and reuse in Selenium RC or Web Driver.
4. Has help and reporting functionalities Built-in.

Cons-
1. Only available for Firefox Browser
2.We can only create prototypes of tests.
3. Cannot add iterations and conditions operator.
4. Test Execution Requires more time.

 

Selenium RC

Selenium Remote Control was  the first Testing framework to allow users to use a programming language they prefer. Selenium RC supports Java, C#,PHP,Python ,perl, Ruby.

Pros-
1. Supports Cross browser and cross platform testing.
2. We can add iteration and condition operators in our test code.
3. It also supports faster execution as compared to Selenium IDE.
4. Comes with List handy APIs to perform advance testing.
5. We can perform data-driven testing using Selenium RC.

Cons-
1. One must have a programming knowledge to use Selenium RC.
2. For Test Execution running instance of Selenium RC server is required.
3.Slower test execution time as compared to Selenium Web Driver.
4. Selenium RC uses Java scripts causing inconsistent.

 

Selenium Web Driver

Selenium web driver is much more powerful testing framework as compared to Selenium IDE and RC. It supports all the languages supported by Selenium RC but it does not use Javascript and hence makes the test case more consistent.

Pros-
1. Test Cases written using Selenium Web Driver Directly communicates with Browser without any server in-between.
2. Faster in Execution.

Cons -
1. This does not support new browsers readily

 

Selenium Grid

Selenium Grid tool is used to run the test cases in parallel with different browsers at the same time. It makes use of Hub and  node concepts and saves time efficiently for tests case execution.

I hope this help you to understand basics of selenium and test suits provided by selenium. If you find it useful then share with your friends.Share your questions and feedback in the comment section given below.





Tuesday 11 October 2016

Selenium APIs To Locate Elements

In our previous tutorials we have seen that how to inspect the web page to get the HTML code. On the basis of this HTML code we have also seen that how to find XPATH to locate elements. Apart from Xpath there are different ways to locate an element using APIs provided by selenium tool. 

In our test case we are going to write the series of steps which we want to automate like clicking on a button and entering text in textbox.To do so we need to find out on which button we want to click and pass it on to Selenium API.

Le us see Most commonly used APIs with simple examples.

1. Find By ID

HTML = <button id="submit1" class="cname" > Submit </button>

Selenium = WebElement submitbutton= driver.findElement(By.id("submit1"));

2. Find by Link

HTML = <a href="http://www.qaautomated.com" > Click Here </a>

Selenium = WebElement linkText= driver.findElement(By.linkText("Click Here"));

3. Find by Class Name

HTML = <button id="submit1" class="cname" > Submit </button>

Selenium = WebElement submitButton= driver.findElement(By.class("cname"));

4. Find by Partial Link

HTML = <a href="http://www.qaautomated.com" > Click Here </a>

Selenium = WebElement linkText= driver.findElement(By.partialLinkText("Click"));

5. Find by Xpath

HTML = <button id="submit1" class="cname" > Submit </button>

Selenium = WebElement submitbutton= driver.findElement(By.xpath("//button[@text()='Submit']"));


In this way you can use the HTML code associated with Web Element to locate in your selenium test case so that you can perform actions on them lick click, type text and double click etc.

I hope this post helps you . Please share your feedback and questions in comments section below. This gives me motivation to write more and more.

Video Tutorial - 



Monday 10 October 2016

How to Test AutoComplete Text Box with Espresso

This is the most common test scenario now a days because many apps are using autocomplete textbox / autofill textbox. If you have not yet come across this then you can check out your google map application when you start typing inside location fill then the drop-down list of matching results are displayed and you can select any one from the list to continue.This post is about handing test cases where you need to select a result from autocomplete textbox.

Let us see the below example of google map and let us write Espresso Test Case to handle Autocomplete Textbox value selection.

AutoComplete Textbox Test Automation
AutoComplete Textbox Test Automation

Test Scenario -

1. Type the location name.
2. Check that list of matching results are displayed.
3. Click on any one of the matching results.

Test Case -

1. In the below sample test case we are using Junit Testing Framework.
2. We are defning the main activity of the application by using @Rule Annotation.
3. We are using inRoot() and decor View to select a window inside a Main activity window.
4. First we are typing "Ban" in the location field and then we are checking the first two suggestions are displayed or not.
5. Then we are clicking on the Top suggestion.


@RunWith(AndroidJUnit4.class)
@LargeTest
public class MultiWindowTest {

    @Rule
    public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
            MainActivity.class);

    private MainActivity mActivity = null;

    @Before
    public void setActivity() {
        mActivity = mActivityRule.getActivity();
    }

    @Test
    public void testAutoCompleteTextView() {
        // Type "ban" to trigger two suggestions.
        onView(withId(R.id.auto_complete_text_view))
                .perform(typeText("ban"), closeSoftKeyboard());

        // Check that both suggestions are displayed.
        onView(withText("Bangalore"))
                .inRoot(withDecorView(not(is(mActivity.getWindow().getDecorView()))))
                .check(matches(isDisplayed()));
        onView(withText("bangalore central mall"))
                .inRoot(withDecorView(not(is(mActivity.getWindow().getDecorView()))))
                .check(matches(isDisplayed()));
    }

        // Tap on a suggestion.
        onView(withText("Bangalore"))
                .inRoot(withDecorView(not(is(mActivity.getWindow().getDecorView()))))
                .perform(click());

        // By clicking on the auto complete term, the text should be filled in.
        onView(withId(R.id.auto_complete_text_view))
                .check(matches(withText("Bangalore")));
    }

    

}

I hope this post helps you to resolve your autocomplete textbox test issue. If you find it useful then please share with your friends and give me feedback or suggestions in the comment section given below.

Sunday 2 October 2016

How to Configure TestNG with Android Studio

In our previous tutorial we have learnt about Junit Testing framework  and now in this we will get to know about one more powerful testing framework called TestNG. TestNG framework as some different functionalities which makes it more powerful testing framework.
What is TestNG Framework?
TestNG is a testing framework developed from inspiration of Junit and Nunit with additional features making is more effective and simple for use. It is a powerful automation testing framework where NG Stands for Next Generation. It gives developers power to write more flexible and powerful test cases.

Features of TestNG –
1.It allows you to use new features of Java programming language while writing test cases.
2.Like Junit it provides annotations to identify your test methods and flow of execution.
3.Separates compile time test code and run time configurations.
4.Provides powerful test case execution support.
5.Allows you to perform multithreading testing.
6.Initially It was designed for unit testing but now allows load testing , parallel testing etc.

There is so much more in this and  we will explore more and more when we start coding. But it is very important to learn basics about Testing frameworks before writing your test cases as selection of right framework is like building pillar for your automation framework.

How to Setup TestNG –

1. Create and Android Project or open your existing project
2. Go to app -> build.gradle
3. Copy the below line of code in your dependencies section.
       testCompile 'org.testng:testng:6.9.10'




4. Click on Sync
5. Once you get build successful message then you are ready to go.

Basics of Android Project Structure

Coding with android studio looks very promising because it is an IDE based on IntelliJ IDEA that is used for android application development. Even though we are not going to build android application, it is very important for us to understand the project structure so that we can code effective and understandable automation test framework.
There are five important components of Android Project Structure like main,gradle,.idea, app and External Libraries. Let us Discuss this in detail.

1. Main Project –This would be entire project context. Whatever you do in IntelliJ IDEA, you do that in the context of a project. A project is an organizational unit that represents a complete software solution. A project in Android Studio is like a workspace . In android Studio a project, can contain multiple modules. This means that, in theory it is possible to build multiple apps within the same project.

2. .idea –.idea is used for storing project specific metadata in Android Studio.

3. Project Module –This is the actual project folder where your application code resides. The application folder has following sub directories.
   a) build: This has all the complete output of the make process i.e. classes.dex, compiled classes and resources, etc.
  b) libs : The lib folder is used for storing project specific jar files.
  c) src: The src folder can have both application code and android unit test script. You will find two folders named “androidTest” and “main” correspond to src folder. The main folder contains two subfolders java and res. The java folder contains all the java codes and res contains drawables, layouts, etc.

4. Gradle – Gradle is used for configuration of build procress. We will see more detais about this in our nest post.

5. External Libraries -This is a place where Referenced Libraries and information on targeted platform SDK is shown.

Android Project Structure
Android Project Structure

How to Debug Code with Android Studio ?

Debugging your code to find out the flow of test case execution id very important for Mobile Automation Testing because if there is a test case execution error then we can find it easily and fix it quickly.

Android Studio  provides the shortcuts keys to debug your code and check for the root cause. Do try out below steps to debug your test case. Open any of your test case written in Android Studio.

1. Setting up debug pointer - Debug pointer means pin point a line of code from where you want to start debug mode and run your code one by one.left side of your code just perform a single click and then you will see a red dot which indicated the Debug Pointer.
 

2. Run Test Case in Debug Mode -  Right click on Test Class Name  -> Debug as ''Test Class Name'.


3. Debug Console -  As soon as you run the test code in Debug Mode, the code runs till the Debug Pointer and then at the bottom part of Android Studio a new window opens up which is called as Debug Console. It gives control in our hands now to run the code line by line.

4. Press the button highlighted in the below screenshot for recording the test code line by line. Each time you press the button the selected line of code will get executed.


5. If you got the error which you were looking for and now you want to run the entire set of code then press the button highlighted in the below window.


6. If you want to check out the variable value then open Variable Console and find out.

This is very simple and important thing to learn while writing Automation Code. Share with people who are working for Mobile Automation and spending more time on debugging test code. Happy Testing :)

How to Perfrom Vertical Scroll without using scrollTo() in Appium ?



I have already written How To Perform Vertical Scroll using scrollTo()? But if you have updated with new Java Client 4.1.2 then you will notice that scrollTo() method is deprecated. So In this post I am going to explain an alternative way to perform Vertical Scroll. It is very simple and easy to understand hence lets begin.

Test Case Scenario -

1. Launch the application
2. Perform vertical scroll

Finding X-Coordinate -
We need y co-ordinates of the screen  and to find that there are two ways -
1. Using Pointer Location-
    * Go to phones Settings
    * Click on Developer Options
    * Enable Pointer Location 
    * open your app and click on the mid of the horizontal tab and then you will get x and y
       coordinates but note down x- coordinates.

2. Using UI automator - 
   *Open UIAutomator Inspector.
   * Take screen shot.
   * Click on middle of the horizontal tab and note down x-coordinates displayed at top right corner.

Test Case -
1. We will implement verticalScroll() method. In this method we will get the screen size with that we can find our start point and end point as we are going o scroll. We also have x co-ordinates so we can use driver.swipe() to perform vertical scroll as shown below
2. We are using for loop to scroll till we find the expected text.


@Test
    public void testScroll()throws Exception
    {
        for(int i=0;i<4;i++)
        {
            Thread.sleep(2000);
            if (driver.findElement(By.name("end_item")).isDisplayed())
            {
                driver.findElement(By.name("end_item")).click();
                break;
            }
            else
            {
                verticalScroll();
            }

        }
    }
    public void verticalScroll()
    {
        size=driver.manage().window().getSize();
        int y_start=(int)(size.height*0.60);
        int y_end=(int)(size.height*0.30);
        int x= size.width / 2;
        driver.swipe(x,y_start,x,y_end,4000);
    }

with this post you can write test code for Vertical Scroll up to specified dimensions , Vertical Scroll till you find the element  and vertical scroll till the end.

I hope you find this tutorial useful. Do share your feedback and questions in comments section below.Please follow me on social media to get latest post updates.