Scroll to element appium java

360learntocode

In this post, I will show you how to do scrolling in Appium. Appium provides the TouchAction API for gesture implementation.

 import io.appium.java_client.android.AndroidDriver; import org.junit.After; import org.junit.Before; import org.openqa.selenium.remote.DesiredCapabilities; import org.openqa.selenium.support.ui.WebDriverWait; import java.net.MalformedURLException; import java.net.URL; public class AppiumTest < private static AndroidDriver driver; private static WebDriverWait wait; @Before public static void setUp() throws MalformedURLException < DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability("platformName", "Android"); cap.setCapability("deviceName", "your device name"); cap.setCapability("appPackage", "appPackage"); cap.setCapability("appActivity", "appActivity"); cap.setCapability("automationName", "UiAutomator1"); cap.setCapability("autoGrantPermissions", true); cap.setCapability("autoAcceptAlerts", "true"); driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap); wait = new WebDriverWait(driver,60); >@After public static void tearDown() < driver.quit(); >> 
 //AppiumTest.java private static void scroll(int scrollStart, int scrollEnd)

Here, we are dealing with scrolling, so we are adjusting the value for the y-axis. The press() method allows you to press on the position x, y coordinates. You can use some offset value for x coordinate instead of 0 x-offset value. The waitAction() method will wait until the duration provided. The moveTo() method allows moving current touch action to a new position specified. The release() method removes the touch. Next, we will adjust the scrollStart and scrollEnd arguments to move down and up.

 //AppiumTest.java public static void scrollDown() < MobileElement element = (MobileElement) driver.findElement(By.id("resourceId")); if (element == null)< return; >int numberOfTimes = 10; Dimension dimension = driver.manage().window().getSize(); int windowsHeight = dimension.getHeight(); int scrollStart = (int) (windowsHeight * 0.5); int scrollEnd = (int) (windowsHeight * 0.3); int elementLocationOffset = windowsHeight-500; for (int i = 0; i < numberOfTimes; i++) < int elementLocationY = element.getLocation().y; if (elementLocationY < elementLocationOffset)< i = numberOfTimes; System.out.println("Element available."); >else < scroll(scrollStart, scrollEnd); System.out.println("Element not available. Scrolling. "); >> > 

In the above scrolling down example, we are trying to scroll down until the element is visible on the screen. Here, we are getting the dimension of the screen window; as we are scrolling so, we use windows height to manipulate the position to scroll.

For e.g, if windows height is 1000 scrollStart will be 500 and scrollEnd will be 300 which means while calling scroll() method it will press to the position (x,y) (0, 500) and move to (x,y)(0, 300) which results in scrolling downward. We are looping so that it will scroll down until the element will arrive to the elementLocationOffset position where the element will be visible on the screen.

For testing element availability, if the above approach doesn’t work you can try finding the element as below:

 int scrollStart = (int) (windowsHeight * 0.3); int scrollEnd = (int) (windowsHeight * 0.7); 
For e.g: if the window’s height is 1000 then scrollStart will be 300 and scrollEnd will be 700 which means while calling scroll() method it will press to the position (x,y) (0, 300) and move to (x,y)(0, 700) which results in scrolling upward. Adjust the value that suits you.

The overall Implementation looks like below:
 package appium; import io.appium.java_client.MobileElement; import io.appium.java_client.TouchAction; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.touch.WaitOptions; import org.junit.After; import org.junit.Before; import org.openqa.selenium.By; import org.openqa.selenium.Dimension; import org.openqa.selenium.remote.DesiredCapabilities; import java.net.MalformedURLException; import java.net.URL; import java.time.Duration; import static io.appium.java_client.touch.offset.PointOption.point; public class AppiumTest < private static AndroidDriver driver; @Before public static void setUp() throws MalformedURLException < DesiredCapabilities cap = new DesiredCapabilities(); cap.setCapability("platformName", "Android"); cap.setCapability("deviceName", "your device"); cap.setCapability("appPackage", "appPackage"); cap.setCapability("appActivity", "appActivity"); cap.setCapability("automationName", "UiAutomator1"); cap.setCapability("autoGrantPermissions", true); cap.setCapability("autoAcceptAlerts", "true"); driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), cap); >public static void scrollDown() < MobileElement element = (MobileElement) driver.findElement(By.id("resourceId")); if (element == null)< return; >int numberOfTimes = 10; Dimension dimension = driver.manage().window().getSize(); int windowsHeight = dimension.getHeight(); int scrollStart = (int) (windowsHeight * 0.5); int scrollEnd = (int) (windowsHeight * 0.3); int elementLocationOffset = windowsHeight-500; for (int i = 0; i < numberOfTimes; i++) < int elementLocationY = element.getLocation().y; if (elementLocationY < elementLocationOffset)< i = numberOfTimes; System.out.println("Element available."); >else < scroll(scrollStart, scrollEnd); System.out.println("Element not available. Scrolling. "); >> > private static void scroll(int scrollStart, int scrollEnd) < new TouchAction(driver) .press(point(0, scrollStart)) .waitAction(WaitOptions.waitOptions(Duration.ofSeconds(1))) .moveTo(point(0, scrollEnd)) .release().perform(); >@After public static void tearDown() < driver.quit(); >> 

Источник

Читайте также:  Алгоритм джонсона троттера java

How to scroll down to an element in Appium

The rise in the number of smartphone users globally over the years has led to the advent of Android and IOS apps. This brought a wave into the mobile market and the need to build mobile apps.

Number of Smartphone users Globally

Businesses got their own apps to provide a seamless experience so that the users could avail of their services with just one click having all the apps on one single device. This made testing of mobile apps so vital that our testing community progressed towards automation testing on top of manual testing.

What does “Scroll down to the element” mean?

Scroll Dowm to Element

Since the automation tests need code to be executed, some important scenarios require special attention and need to have the test suite run without errors and glitches for a better user experience.

One such scenario is performing an action on an element that is present on an application but not visible on the current page. This case requires scrolling down the page till the element is visible and performing the required action. One such example is the food ordering app where we need to scroll down to have a glimpse of all dishes available or the OTT apps where we will be scrolling down to check out all sorts of different movie/series content.

When automating an app for testing purposes, you might need to automate the above scenario. This article discusses how to scroll down to an element and perform an action on it in Appium.

How to Scroll until Element is Visible in Appium using visibleUiScrollable

While several Mobile Test Automation tools are available in the market, the most popular among them is Appium. Appium comes up with a rich class UiScrollable , which makes it possible to scroll down to the page and perform actions on elements. It is a powerful Android class that performs element lookups in scrollable layouts. scrollIntoView class performs scroll action until the destination element is found on the screen. UiScrollable is a UiCollection and provides support for searching for items in scrollable layout elements. This class can be used with horizontally or vertically scrollable controls.

Читайте также:  My html page

You can use UiScrollable swipe to search elements in a list or search elements outside of the screen like input field, text or button. ScrollIntoView has UiSelector as a search criteria input that allows it to find elements by text or id.

Make sure you have all software installed and running in your system.

In this example, taking a sample APK to automate using Appium. You can get some sample test apk’s on your system on below path:

C:\Users\singe\AppData\Local\Android\Sdk\system-images\android-25\google_apis\x86\data\app

Using one such apk ‘ API Demos ’ for this article. Automation test will launch the app, click on ‘Views’ and will locate ‘WebView’ by scrolling down the list and clicking over it as seen in the image below.

Scroll Down to Element in Appium ExampleScroll Down to Element in Appium Examples

Make sure you have all the Appium and testing dependencies configured on your system such as:

  1. Create a new java project.
  2. Create a package and a class
  3. Add all required capabilities
  4. Function to scroll down and take action

Browserstack Capabilities Generator in Appium

Code to Scroll Down until Element is Visible in Appium

The following code uses UiScrollable(), scrollIntoView(), UiSelector(), and scrollable() to scroll down to an element until it is visible using Appium.

package testing; import org.testng.annotations.Test; import org.openqa.selenium.remote.DesiredCapabilities; import io.appium.java_client.android.AndroidDriver; import java.net.URL; import java.util.concurrent.TimeUnit; public class scrolldown @Test public void scroll() try  DesiredCapabilities caps = new DesiredCapabilities(); caps.setCapability("deviceName", "Google pixel 4"); //Give your device/emulator name caps.setCapability("udid", "emulator-5554"); // Go to adb location i.e. C:\Users\singe\AppData\Local\Android\Sdk\platform-tools in command prompt and execute ‘adb devices’ to get udid caps.setCapability("platformVersion", "8.1.0"); //Give android version of your device. (Check ‘about phone’ section) caps.setCapability("appPackage", "com.hmh.api"); //provide app package name. Apkinfo can be used or execute dumpsys window windows | grep -E ‘mCurrentFocus’ command in adb shell in cmd in C:\Users\singe\AppData\Local\Android\Sdk\platform-tools caps.setCapability("appActivity", "com.hmh.api.ApiDemos"); AndroidDriver driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), caps); //Create driver object driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); //Implicit wait of 10 seconds driver.findElementByXPath("//*[contains(@text,'Views')]").click(); driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\"WebView\").instance(0))").click(); //scroll down to the element and click Thread.sleep(10000); //wait of 10 seconds driver.quit(); //closes the driver session > catch (Exception e) // TODO Auto-generated catch block e.printStackTrace(); > > >

By following the above example, you can automate any scroll scenarios using Appium. For accurate results, it’s advisable to make use of cross-platform testing tools and increase test coverage by a hundred times by testing your app on multiple versions of operating systems and different Android and iOS devices. Real Device Cloud like Browserstack provides this platform where you can integrate your Appium tests with thousands of available real devices using App Automate .

After integration with BrowserStack App Automate, the code will look like below:

package testing; import java.net.URL; import java.util.List; import java.util.function.Function; import java.net.MalformedURLException; import io.appium.java_client.MobileBy; import io.appium.java_client.android.AndroidDriver; import io.appium.java_client.android.AndroidElement; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.openqa.selenium.WebDriver; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.Test; public class BrowserStackSample public static void main(String[] args) throws MalformedURLException, InterruptedException DesiredCapabilities caps = new DesiredCapabilities(); // Set your access credentials caps.setCapability("browserstack.user”, ); caps.setCapability("browserstack.key", ); // Set URL of the application under test caps.setCapability("app", "bs://d74ed9c2bd06fb02d7b863b3f1a7f8dfe97092b7" ); // Specify device and os_version for testing caps.setCapability("device", "Samsung Galaxy S5"); caps.setCapability("os_version", "4.4"); // Set other BrowserStack capabilities caps.setCapability("project", "First Java Project"); caps.setCapability("build", "browserstack-build-1"); caps.setCapability("name", "first_test"); // Initialise the remote Webdriver using BrowserStack remote URL // and desired capabilities defined above AndroidDriver driver = new AndroidDriver( new URL("http://hub.browserstack.com/wd/hub"), caps); // Test case for the BrowserStack sample Android app. // If you have uploaded your app, update the test case here. //driver.findElementByName("Cancel").click(); driver.findElementByXPath("//*[contains(@text,'Views')]").click(); driver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0)).scrollIntoView(new UiSelector().textContains(\"WebView\").instance(0))").click(); Thread.sleep(5000); // Invoke driver.quit() after the test is done to indicate that the test is completed. driver.quit(); > >

Test Results

Scroll Down to Element in Appium Test Results

Test results can be viewed on App Automate Dashboard once the test execution is completed. By clicking on individual tests will give you a detailed report for each test including steps, text logs , Appium logs, execution video logs, and other details for better debugging of failed tests.

Источник

Оцените статью