Best io.appium code snippet using io.appium.java_client.AppiumBy
AppiumAppTest.java
Source:AppiumAppTest.java
2import java.net.URL;3import org.openqa.selenium.WebElement;4import org.openqa.selenium.interactions.Actions;5import org.openqa.selenium.remote.DesiredCapabilities;6import io.appium.java_client.AppiumBy;7import io.appium.java_client.android.AndroidDriver;8public class AppiumAppTest {9 static DesiredCapabilities dc = new DesiredCapabilities();10 static {11 dc.setCapability("deviceName", "Nexus_5_API_30");12 dc.setCapability("udid", "emulator-5554");13 dc.setCapability("platformName", "Android");14 dc.setCapability("platformVersion", "11.0");15 dc.setCapability("appPackage", "com.example.myapp");16 dc.setCapability("appActivity", "com.example.myapp.MainActivity");17 }18 static final String url = "http://127.0.0.1:4723/wd/hub";19 static int successfulTestCount;20 private AndroidDriver driver;21 22 public boolean isConnected() {23 if(driver == null)24 return false;25 return true;26 }27 28 public void connectServer() throws MalformedURLException {29 driver = new AndroidDriver(new URL(AppiumAppTest.url), dc);30 System.out.println("Connection established to server");31 32 }33 /** // 1. test: Anasayfa */34 public void test1() {35 // 1. test: Anasayfa36 if(!this.isConnected()) {37 System.err.println("Once server'a baglanin lutfen");38 return;39 }40 WebElement element = null;41 String currentPageText = new String();42 try {43 // tek erisim elemani xpath oldugundan onu kullandik, tavsiye edilmez44 element = driver.findElement(AppiumBy.xpath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.view.ViewGroup/android.widget.FrameLayout[1]/android.view.ViewGroup/android.widget.TextView"));45 currentPageText = element.getText();46 if (currentPageText.equalsIgnoreCase("anasayfa"))47 System.out.println("Anasayfa Testi Basarili");48 else49 System.out.println("Anasayfa Testi Basarisiz");50 } catch (Exception e) {51 System.err.println("Anasayfa Yazisi Bulunamadi");52 }53 }54 /** // 2.1. Test: Anasayfa slayt // 2.2 Bilgi Yazisi */55 public void test2() {56 57 if(!this.isConnected()) {58 System.err.println("Once server'a baglanin lutfen");59 return;60 }61 Actions actions = new Actions(driver);62 WebElement element = null;63 try {64 element = driver.findElement(AppiumBy.accessibilityId("Slayt"));65 String elementClass = element.getAttribute("class");66 if (elementClass.equalsIgnoreCase("android.widget.imageview")) {67 System.out.println("Slayt Bulundu, Butonlar Deneniyor...");68 try {69 WebElement btn = driver.findElement(AppiumBy.id("com.example.myapp:id/btnSlideLeft"));70 if (btn.getAttribute("clickable").equalsIgnoreCase("True")) {71 actions.moveToElement(btn).click().perform();72 System.out.println("Sol Buton Calisiyor");73 } else {74 System.out.println("Sol Buton Calismiyor");75 }76 btn = driver.findElement(AppiumBy.id("com.example.myapp:id/btnSlideRight"));77 if (btn.getAttribute("clickable").equalsIgnoreCase("True")) {78 actions.moveToElement(btn).click().perform();79 System.out.println("Sag Buton Calisiyor");80 } else {81 System.out.println("Sag Buton Calismiyor");82 }83 } catch (Exception e) {84 System.out.println("Butonlar bulunurken hata");85 }86 }87 } catch (Exception e) {88 System.err.println("Anasayfa Slayti bulunamadi");89 } 90 91 try {92 element = driver.findElement(AppiumBy.id("com.example.myapp:id/tvMainAbout"));93 String text = "Bölümümüzün misyonu Bilgisayar MühendisliÄi alanında bilgi "94 + "ve teknoloji üretmek, üretilen deÄerleri medeniyetlerin "95 + "ilerlemesi için kullanmak, ve yenilikçi ve araÅtırma eksenli "96 + "bir eÄitim vererek kendine güvenen, giriÅimci, eleÅtirel analiz "97 + "yapabilen, teknik ve etik bilgilerle donatılmıÅ, bilgisayar yazılım, "98 + "donanım ve bilgi sistemleri tasarlayabilen, geliÅtirebilen ve "99 + "sürdürebilen mühendisler yetiÅtirmektir.";100 101 if(element.getAttribute("text").equals(text)) {102 System.out.println("Bilgi yazisi dogru bir sekilde bulundu.");103 System.out.println("Yazi sinirlari: " + element.getAttribute("bounds"));104 }105 } catch (Exception e) {106 System.err.println("Bilgi Yazisi Bulunamadi");107 }108 }109 110 /** //open dropdown */111 public void test3a() {112 if(!this.isConnected()) {113 System.err.println("Once server'a baglanin lutfen");114 return;115 }116 WebElement element = null;117 try {118 System.out.println("Dropdown acilisi test ediliyor...");119 element = driver.findElement(AppiumBy.accessibilityId("Open navigation"));120 element.click();121 System.out.println("Dropdown aciliyor.");122 } catch (Exception e) {123 System.err.println("Dropdown Acilmiyor.");124 }125 }126 /** /close dropdown */127 public void test3b() {128 if(!this.isConnected()) {129 System.err.println("Once server'a baglanin lutfen");130 return;131 }132 WebElement element = null;133 try {134 System.out.println("Dropdown kapanisi test ediliyor...");135 element = driver.findElement(AppiumBy.accessibilityId("Close navigation"));136 element.click();137 System.out.println("Dropdown kapaniyor.");138 } catch (Exception e) {139 System.err.println("Dropdown Kapanmiyor.");140 }141 }142 /**143 //urun secenekleri144 //dropdown acmadan kullanmayin145 */146 public void test4() {147 if(!this.isConnected()) {148 System.err.println("Once server'a baglanin lutfen");149 return;150 }151 WebElement urun1 = null;152 WebElement urun2 = null;153 try { 154 System.out.println("Urunler kontrol ediliyor...");155 //yetiskin urun156 urun1 = driver.findElement(AppiumBy.id("com.example.myapp:id/miProductAdult"));157 158 if(urun1.getAttribute("clickable").equalsIgnoreCase("true"))159 System.out.println("Yetiskin urunleri bulundu");160 161 urun2 = driver.findElement(AppiumBy.id("com.example.myapp:id/miProductChild"));162 if(urun2.getAttribute("clickable").equalsIgnoreCase("true"))163 System.out.println("Cocuk urunleri bulundu");164 165 System.out.println("Urun secenekleri basarili.");166 } catch (Exception e) {167 System.err.println("Urunler Sekmesi Elemanlari Yetersiz ya da Bulunamadi");168 }169 }170 /**171 yetiskin urun sayfa sol-sag butonlari172 dropdown acmadan kullanmayin173 */174 public void test5a() {175 WebElement adltBtnLeft = null;176 WebElement adltBtnRight = null;177 WebElement urun1 = null;178 try {179 urun1 = driver.findElement(AppiumBy.id("com.example.myapp:id/miProductAdult"));180 urun1.click();181 System.out.println("Yetiskin butonlari deneniyor...");182 try {183 adltBtnRight = driver.findElement(AppiumBy.id("com.example.myapp:id/btnRight"));184 for (int i = 0; i < 6; i++) {185 adltBtnRight.click();186 }187 188 if(driver.findElement(AppiumBy.xpath("/hierarchy/android.widget.Toast")).getText().equalsIgnoreCase("zaten son sayfadasınız."))189 System.out.println("Ileri buton calisiyor");190 191 192 } catch (Exception e) {193 System.err.println("Ileri butonu bulunurken hata");194 }195 System.out.println("Geri butonu bekleniyor");196 try { 197 Thread.sleep(5000);198 adltBtnLeft = driver.findElement(AppiumBy.id("com.example.myapp:id/btnLeft"));199 200 for (int i = 0; i < 6; i++) {201 adltBtnLeft.click();202 }203 204 if(driver.findElement(AppiumBy.xpath("/hierarchy/android.widget.Toast")).getText().equalsIgnoreCase("zaten ilk sayfadasınız."))205 System.out.println("Geri buton calisiyor");206 207 } catch (Exception e) {208 System.err.println("Geri buton bulunurken hata");209 }210 } catch (Exception e) {211 System.err.println("Yetiskin ekranina gidilemedi");212 }213 }214 /**215 cocuk urun sayfa sol-sag butonlari216 dropdown acmadan kullanmayin217 */218 public void test5b() {219 WebElement urun2 = null;220 WebElement chldBtnLeft = null;221 WebElement chldBtnRight = null;222 try {223 urun2 = driver.findElement(AppiumBy.id("com.example.myapp:id/miProductChild"));224 urun2.click();225 System.out.println("Cocuk butonlari deneniyor...");226 try {227 chldBtnLeft = driver.findElement(AppiumBy.id("com.example.myapp:id/btnLeftChild"));228 chldBtnRight = driver.findElement(AppiumBy.id("com.example.myapp:id/btnRightChild"));229 230 for (int i = 0; i < 6; i++) {231 chldBtnRight.click();232 }233 if(driver.findElement(AppiumBy.xpath("/hierarchy/android.widget.Toast")).getText().equalsIgnoreCase("zaten son sayfadasınız."))234 System.out.println("Ileri buton calisiyor");235 } catch (Exception e) {236 System.err.println("Ileri butonu bulunurken hata");237 }238 System.out.println("Geri butonu bekleniyor");239 try {240 Thread.sleep(5000);241 for (int i = 0; i < 6; i++) {242 chldBtnLeft.click();243 }244 245 if(driver.findElement(AppiumBy.xpath("/hierarchy/android.widget.Toast")).getText().equalsIgnoreCase("zaten ilk sayfadasınız."))246 System.out.println("Geri buton calisiyor");247 } catch (Exception e) {248 System.err.println("Geri butonu bulunurken hata");249 }250 } catch (Exception e) {251 System.err.println("Cocuk ekranina gidilemedi");252 }253 }254 public static void main(String[] args) {255 AppiumAppTest a1 = new AppiumAppTest();256 try {257 a1.connectServer();258 a1.test1();259 a1.test2();...
sampleTestAOSapp_Android.java
Source:sampleTestAOSapp_Android.java
1import io.appium.java_client.AppiumBy;2import io.appium.java_client.android.AndroidDriver;3import io.appium.java_client.android.options.UiAutomator2Options;4import org.junit.*;5import org.openqa.selenium.support.ui.ExpectedConditions;6import org.openqa.selenium.support.ui.WebDriverWait;78import java.net.URL;9import java.time.Duration;10import java.util.concurrent.TimeUnit;1112public class sampleTestAOSapp_Android {13 private AndroidDriver driver;14 private String SERVER = "http://uftm-server:8080";1516 @Before17 public void setUp() throws Exception {18 UiAutomator2Options caps = new UiAutomator2Options();19 caps.setCapability("platformName", "Android");20 caps.setCapability("udid", "RF8N879MPYH");21 caps.setCapability("automationName", "UiAutomator2");22 caps.setCapability("appPackage", "com.Advantage.aShopping");23 caps.setCapability("appActivity", "com.Advantage.aShopping.SplashActivity");24 caps.setCapability("uftm:oauthClientId", "oauth2-m2pbTT3wUdAvsdBJXr0w@microfocus.com");25 caps.setCapability("uftm:oauthClientSecret", "tcNG3V5YVdjbgJhPl3Vl");26 caps.setCapability("uftm:tenantId", "999999999");27 driver = new AndroidDriver(new URL(SERVER + "/wd/hub"), caps);28 }2930 @After31 public void teardown(){32 if (driver != null) {33 driver.quit();34 }35 }3637 @Test38 public void testAOSapp(){39 //Implicit wait40 driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));41 driver.findElement(AppiumBy.xpath(42 "//android.view.ViewGroup[@content-desc=\"Home Page\"]/android.widget.LinearLayout[2]/android.widget.LinearLayout/android.support.v7.widget.RecyclerView/android.widget.RelativeLayout[1]/android.widget.TextView"))43 .click();44 driver.findElement(AppiumBy.xpath(45 "//android.widget.RelativeLayout[@content-desc=\"Laptops\"]/android.widget.LinearLayout/android.widget.GridView/android.widget.RelativeLayout[4]/android.widget.TextView[1]"))46 .click();47 driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/linearLayoutProductDetails")).click();48 driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/imageViewProductDetailsClose")).click();49 driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/linearLayoutProductQuantity")).click();50 driver.findElement(AppiumBy.xpath(51 "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.LinearLayout[2]/android.widget.ImageView[2]"))52 .click();53 driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/textViewApply")).click();54 driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/buttonProductAddToCart")).click();55 driver.findElement(AppiumBy.xpath(56 "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.LinearLayout[2]/android.widget.RelativeLayout[3]/android.widget.EditText"))57 .sendKeys("Username");58 driver.findElement(AppiumBy.xpath(59 "/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.LinearLayout[2]/android.widget.RelativeLayout[4]/android.widget.EditText"))60 .sendKeys("password");61 driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/buttonLogin")).click();62 String ErrorMessage = driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/textViewFailed")).getText();63 assert ErrorMessage.contains("Incorrect user");64 driver.navigate().back();65 driver.navigate().back();66 driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/imageViewMenu")).click();67 driver.findElement(AppiumBy.id("com.Advantage.aShopping:id/textViewMenuHome")).click();6869 }7071}7273
...
GestureTest.java
Source:GestureTest.java
1package com.example.gestures;2import com.google.common.collect.ImmutableMap;3import io.appium.java_client.AppiumBy;4import io.appium.java_client.AppiumDriver;5import io.appium.java_client.android.AndroidDriver;6import io.appium.java_client.android.options.UiAutomator2Options;7import org.openqa.selenium.Point;8import org.openqa.selenium.Rectangle;9import org.openqa.selenium.WebElement;10import org.openqa.selenium.interactions.Pause;11import org.openqa.selenium.interactions.PointerInput;12import org.openqa.selenium.interactions.Sequence;13import org.openqa.selenium.logging.LogType;14import org.openqa.selenium.logging.LoggingPreferences;15import org.openqa.selenium.remote.RemoteWebElement;16import org.openqa.selenium.remote.http.HttpMethod;17import org.openqa.selenium.support.ui.ExpectedConditions;18import org.openqa.selenium.support.ui.WebDriverWait;19import org.testng.annotations.BeforeClass;20import org.testng.annotations.Test;21import java.net.URL;22import java.time.Duration;23import java.util.logging.Level;24import static java.time.Duration.*;25import static java.time.Duration.ofMillis;26import static java.util.Collections.singletonList;27import static org.openqa.selenium.support.ui.ExpectedConditions.elementToBeClickable;28import static org.openqa.selenium.support.ui.ExpectedConditions.presenceOfElementLocated;29public class GestureTest {30 public AppiumDriver driver;31 public WebDriverWait wait;32 @BeforeClass33 public void beforeClass() throws Exception {34 UiAutomator2Options options = new UiAutomator2Options()35 .setDeviceName("Android Emulator")36 .setApp(System.getProperty("user.dir") + "/apps/VodQA.apk");37 driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), options);38 wait = new WebDriverWait(driver, ofSeconds(30));39 }40 @Test41 public void dragAndDropTest() {42 wait.until(elementToBeClickable(AppiumBy.accessibilityId("login"))).click();43 wait.until(elementToBeClickable(AppiumBy.accessibilityId("dragAndDrop"))).click();44 final WebElement dragMe = wait.until(presenceOfElementLocated(AppiumBy.accessibilityId("dragMe")));45 final WebElement dropzone = wait.until(elementToBeClickable(AppiumBy.accessibilityId("dropzone")));46 final Point point = dragMe.getRect().getPoint();47 final Rectangle rect = dropzone.getRect();48 final int targetX = rect.getX() + rect.getWidth() / 2;49 final int targetY = rect.getY() + rect.getHeight() / 2;50 PointerInput finger = new PointerInput(PointerInput.Kind.TOUCH, "finger");51 Sequence dragAndDrop = new Sequence(finger, 1);52 // pointerMove, pointerDown, pause, pointerMove, pointerUp53 dragAndDrop.addAction(finger.createPointerMove(Duration.ofMillis(0), PointerInput.Origin.viewport(),54 point.getX(), point.getY()));55 dragAndDrop.addAction(finger.createPointerDown(PointerInput.MouseButton.LEFT.asArg()));56 dragAndDrop.addAction(new Pause(finger, Duration.ofMillis(600)));57 dragAndDrop.addAction(finger.createPointerMove(Duration.ofMillis(600), PointerInput.Origin.viewport(),58 targetX, targetY));59 dragAndDrop.addAction(finger.createPointerUp(PointerInput.MouseButton.LEFT.asArg()));60 driver.perform(singletonList(dragAndDrop));61 }62 @Test63 public void dragAndDropUsingAppiumPluginTest() {64 wait.until(elementToBeClickable(AppiumBy.accessibilityId("login"))).click();65 wait.until(elementToBeClickable(AppiumBy.accessibilityId("dragAndDrop"))).click();66 final WebElement dragMe = wait.until(presenceOfElementLocated(AppiumBy.accessibilityId("dragMe")));67 final WebElement dropzone = wait.until(elementToBeClickable(AppiumBy.accessibilityId("dropzone")));68 driver.addCommand(HttpMethod.POST, String.format("/session/%s/plugin/actions/dragAndDrop",69 driver.getSessionId()), "dragAndDrop");70 driver.execute("dragAndDrop", ImmutableMap.of("sourceId", ((RemoteWebElement) dragMe).getId(),71 "destinationId", ((RemoteWebElement) dropzone).getId()));72 }73}...
SwagLabsLoginIos.java
Source:SwagLabsLoginIos.java
1import io.appium.java_client.AppiumBy;2import io.appium.java_client.PerformsTouchActions;3import io.appium.java_client.TouchAction;4import io.appium.java_client.ios.IOSDriver;5import io.appium.java_client.touch.WaitOptions;6import io.appium.java_client.touch.offset.PointOption;7import org.openqa.selenium.By;8import org.openqa.selenium.WebDriver;9import org.openqa.selenium.remote.DesiredCapabilities;10import org.testng.annotations.Test;11import java.net.MalformedURLException;12import java.net.URL;13import java.time.Duration;14public class SwagLabsLoginIos {15 @Test16 public void login() throws MalformedURLException, InterruptedException {17 DesiredCapabilities capabilities=new DesiredCapabilities();18 capabilities.setCapability("platformName", "iOS");19 capabilities.setCapability("deviceName", "iPhone 13");20 capabilities.setCapability("automationName", "XCUITest");21 capabilities.setCapability("udid", "CB3931EC-0B2F-4763-AF77-723B5751DC2E");22 capabilities.setCapability("bundleId", "com.saucelabs.SwagLabsMobileApp");23 capabilities.setCapability("app", "/Users/gowthamipv/IdeaProjects/LoginPageios/src/test/resources/app/iOS.Simulator.SauceLabs.Mobile.Sample.app.2.7.1.app");24 IOSDriver driver = new IOSDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);25 Thread.sleep(3000);26 driver.findElement(By.xpath("//XCUIElementTypeTextField[@name=\"test-Username\"]")).sendKeys("standard_user");27 Thread.sleep(3000);28 driver.findElement(By.xpath("//XCUIElementTypeSecureTextField[@name=\"test-Password\"]")).sendKeys("secret_sauce");29 Thread.sleep(3000);30 driver.findElement(By.xpath("//XCUIElementTypeOther[@name=\"test-LOGIN\"]")).click();31 Thread.sleep(3000);32 driver.findElement(By.xpath("(//XCUIElementTypeOther[@name=\"test-ADD TO CART\"])[2]")).click();33 Thread.sleep(3000);34 driver.findElement(By.xpath("(//XCUIElementTypeOther[@name=\"1\"])[4]")).click();35 Thread.sleep(3000);36 TouchAction t = new TouchAction(driver);37 t.tap(PointOption.point(186,657)).perform();38 Thread.sleep(3000);39 driver.findElement(By.xpath("//XCUIElementTypeTextField[@name=\"test-First Name\"]")).sendKeys("Gowthami");40 Thread.sleep(3000);41 driver.findElement(By.xpath("//XCUIElementTypeTextField[@name=\"test-Last Name\"]")).sendKeys("PV");42 Thread.sleep(3000);43 driver.findElement(By.xpath("//XCUIElementTypeTextField[@name=\"test-Zip/Postal Code\"]")).sendKeys("563122");44 Thread.sleep(3000);45 driver.findElement(By.xpath("//XCUIElementTypeOther[@name=\"test-CONTINUE\"]")).click();46 Thread.sleep(3000);47 t.press(PointOption.point(206,762)).waitAction(WaitOptions.waitOptions(Duration.ofMillis((3000)))).moveTo(PointOption.point(215,204)).release().perform();48 Thread.sleep(3000);49 driver.findElement(new AppiumBy.ByAccessibilityId("test-FINISH")).click();50 Thread.sleep(3000);51 driver.findElement(new AppiumBy.ByAccessibilityId("test-BACK HOME")).click();52 Thread.sleep(3000);53 driver.quit();54 }55}...
WebViewTest.java
Source:WebViewTest.java
1package com.ceshiren.hogwarts.wework.app.webview;2import io.appium.java_client.AppiumBy;3import io.appium.java_client.AppiumDriver;4import io.appium.java_client.MobileBy;5import io.appium.java_client.android.AndroidDriver;6import io.appium.java_client.remote.AndroidMobileCapabilityType;7import io.appium.java_client.remote.MobileCapabilityType;8import org.junit.jupiter.api.BeforeAll;9import org.junit.jupiter.api.Test;10import org.openqa.selenium.By;11import org.openqa.selenium.WebElement;12import org.openqa.selenium.remote.CapabilityType;13import org.openqa.selenium.remote.DesiredCapabilities;14import org.openqa.selenium.support.ui.WebDriverWait;15import java.net.MalformedURLException;16import java.net.URL;17import java.time.Duration;18import java.util.Set;19import static org.hamcrest.MatcherAssert.assertThat;20import static org.hamcrest.Matchers.containsString;21public class WebViewTest {22 private static AndroidDriver driver;23 @BeforeAll24 static void beforeAll() throws MalformedURLException {25 DesiredCapabilities capabilities = new DesiredCapabilities();26 capabilities.setCapability(CapabilityType.PLATFORM_NAME, "Android");27 capabilities.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, "io.appium.android.apis");28 capabilities.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, ".ApiDemos");29 capabilities.setCapability("chromedriverExecutableDir", "/Users/seveniruby/projects/chromedriver/chromedrivers");30 capabilities.setCapability("showChromedriverLog", true);31 driver = new AndroidDriver(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);32 driver.manage().timeouts().implicitlyWait(Duration.ofSeconds(10));33 }34 @Test35 void webview() throws InterruptedException {36 driver.findElement(By.cssSelector("*[description=Views]")).click();37 driver.findElement(AppiumBy.androidUIAutomator(38 "new UiScrollable(new UiSelector().scrollable(true))" +39 ".scrollIntoView(new UiSelector().text(\"WebView\"))")).click();40 String webviewContext = "WEBVIEW_io.appium.android.apis";41 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(5));42 wait.until(webDriver -> {43 Set<String> contexts = driver.getContextHandles();44 System.out.println(contexts);45 return contexts.contains(webviewContext);46 });47 driver.context(webviewContext);48 System.out.println(driver.getPageSource());49 System.out.println(driver.getWindowHandles());50 driver.getWindowHandles().forEach(window -> {51 driver.switchTo().window(window);...
AndroidAbilityToUseSupplierTest.java
Source:AndroidAbilityToUseSupplierTest.java
...3import static io.appium.java_client.touch.WaitOptions.waitOptions;4import static io.appium.java_client.touch.offset.ElementOption.element;5import static java.time.Duration.ofSeconds;6import static org.junit.Assert.assertNotEquals;7import io.appium.java_client.AppiumBy;8import io.appium.java_client.functions.ActionSupplier;9import io.appium.java_client.touch.offset.ElementOption;10import org.junit.Test;11import org.openqa.selenium.By;12import org.openqa.selenium.Point;13import org.openqa.selenium.WebElement;14import java.util.List;15public class AndroidAbilityToUseSupplierTest extends BaseAndroidTest {16 private final ActionSupplier<AndroidTouchAction> horizontalSwipe = () -> {17 driver.findElement(By.id("io.appium.android.apis:id/gallery"));18 WebElement gallery = driver.findElement(By.id("io.appium.android.apis:id/gallery"));19 List<WebElement> images = gallery.findElements(AppiumBy.className("android.widget.ImageView"));20 Point location = gallery.getLocation();21 Point center = getCenter(gallery, location);22 ElementOption pressOption = element(images.get(2),-10,center.y - location.y);23 ElementOption moveOption = element(gallery, 10,center.y - location.y);24 return new AndroidTouchAction(driver)25 .press(pressOption)26 .waitAction(waitOptions(ofSeconds(2)))27 .moveTo(moveOption)28 .release();29 };30 private final ActionSupplier<AndroidTouchAction> verticalSwiping = () ->31 new AndroidTouchAction(driver)32 .press(element(driver.findElement(AppiumBy.accessibilityId("Gallery"))))33 .waitAction(waitOptions(ofSeconds(2)))34 .moveTo(element(driver.findElement(AppiumBy.accessibilityId("Auto Complete"))))35 .release();36 @Test public void horizontalSwipingWithSupplier() {37 Activity activity = new Activity("io.appium.android.apis", ".view.Gallery1");38 driver.startActivity(activity);39 WebElement gallery = driver.findElement(By.id("io.appium.android.apis:id/gallery"));40 List<WebElement> images = gallery.findElements(AppiumBy.className("android.widget.ImageView"));41 int originalImageCount = images.size();42 horizontalSwipe.get().perform();43 assertNotEquals(originalImageCount,44 gallery.findElements(AppiumBy.className("android.widget.ImageView")).size());45 }46 @Test public void verticalSwipingWithSupplier() throws Exception {47 driver.resetApp();48 driver.findElement(AppiumBy.accessibilityId("Views")).click();49 Point originalLocation = driver.findElement(AppiumBy.accessibilityId("Gallery")).getLocation();50 verticalSwiping.get().perform();51 Thread.sleep(5000);52 assertNotEquals(originalLocation, driver.findElement(AppiumBy.accessibilityId("Gallery")).getLocation());53 }54}...
sampleTestAOSapp_iOS.java
Source:sampleTestAOSapp_iOS.java
1import io.appium.java_client.AppiumBy;2import io.appium.java_client.ios.options.XCUITestOptions;3import io.appium.java_client.ios.IOSDriver;4import org.junit.*;5import org.openqa.selenium.WebElement;6import org.openqa.selenium.support.ui.ExpectedConditions;7import org.openqa.selenium.support.ui.WebDriverWait;8import java.net.URL;9import java.time.Duration;101112public class sampleTestAOSapp_iOS {13 private IOSDriver driver;14 private String SERVER = "http://uftm-server:8080";1516 @Before17 public void setUp() throws Exception {18 XCUITestOptions caps = new XCUITestOptions();19 caps.setCapability("platformName", "iOS");20 caps.setCapability("udid", "3ecdf8889a8b18cb8858410d1540f3e6b22a2cb1");21 caps.setCapability("bundleId", "com.mf.iShopping");22 caps.setCapability("uftm:oauthClientId", "oauth2-m2pbTT3wUdAvsdBJXr0w@microfocus.com");23 caps.setCapability("uftm:oauthClientSecret", "tcNG3V5YVdjbgJhPl3Vl");24 caps.setCapability("uftm:tenantId", "999999999");25 driver = new IOSDriver(new URL(SERVER + "/wd/hub"), caps);26 }2728 @After29 public void teardown(){30 if (driver != null) {31 driver.quit();32 }33 }3435 @Test36 public void testAOSapp(){37 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10));38 driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"LAPTOPS\"]")).click();39 driver.findElement(AppiumBy.accessibilityId("HP ENVY x360 - 15t Laptop")).click();40 wait.until(ExpectedConditions.presenceOfElementLocated(AppiumBy.accessibilityId("productDetailsButton"))).click();41 driver.findElement(AppiumBy.accessibilityId("Close2")).click();42 driver.findElement(AppiumBy.accessibilityId("quantityButtonId")).click();43 driver.findElement(AppiumBy.accessibilityId("Plus")).click();44 driver.findElement(AppiumBy.accessibilityId("APPLY")).click();45 driver.findElement(AppiumBy.accessibilityId("ADD TO CART")).click();46 driver.findElement(AppiumBy.accessibilityId("Ok")).click();47 driver.findElement(AppiumBy.accessibilityId("userNameLabel")).sendKeys("Username");48 driver.findElement(AppiumBy.accessibilityId("passwordLabel")).sendKeys("password");49 driver.findElement(AppiumBy.accessibilityId("LOGIN")).click();50 WebElement loginErrorText = wait.until(ExpectedConditions.presenceOfElementLocated(51 AppiumBy.accessibilityId("Incorrect user name or password.")));52 assert loginErrorText.isDisplayed() == true;53 wait.until(ExpectedConditions.presenceOfElementLocated(AppiumBy.accessibilityId("Menu"))).click();54 driver.findElement(AppiumBy.accessibilityId("HOME")).click();55 }56}
...
AndroidSampleWithSelenium4Tests.java
Source:AndroidSampleWithSelenium4Tests.java
1//package tests.sample;2//3//import io.appium.java_client.AppiumBy;4//import io.appium.java_client.MobileBy;5//6//import io.appium.java_client.android.AndroidDriver;7//import org.junit.jupiter.api.Test;8//import org.openqa.selenium.WebElement;9//import org.openqa.selenium.remote.DesiredCapabilities;10//import org.openqa.selenium.support.ui.ExpectedConditions;11//import org.openqa.selenium.support.ui.WebDriverWait;12//13//import java.net.MalformedURLException;14//import java.net.URL;15//import java.util.List;16//17//public class AndroidSampleWithSelenium4Tests {18// @Test19// void searchTest() throws MalformedURLException, InterruptedException {20//21// DesiredCapabilities caps = new DesiredCapabilities();22//23// // Set your access credentials24// caps.setCapability("browserstack.user", "tpuretest_lSVWc2");25// caps.setCapability("browserstack.key", "Ggd5nW19cyeGseGGn2m6");26//27// // Set URL of the application under test28// caps.setCapability("app", "bs://c700ce60cf13ae8ed97705a55b8e022f13c5827c");29//30// // Specify device and os_version for testing31// caps.setCapability("device", "Google Pixel 3");32// caps.setCapability("os_version", "9.0");33//34// // Set other BrowserStack capabilities35// caps.setCapability("project", "First Java Project");36// caps.setCapability("build", "browserstack-build-1");37// caps.setCapability("name", "first_test");38//39//40// // Initialise the remote Webdriver using BrowserStack remote URL41// // and desired capabilities defined above42// AndroidDriver driver = new AndroidDriver(43// new URL("http://hub.browserstack.com/wd/hub"), caps);44//45// // Test case for the BrowserStack sample Android app.46// // If you have uploaded your app, update the test case here.47// WebElement searchElement = (WebElement) new WebDriverWait(driver, 30).until(48// ExpectedConditions.elementToBeClickable(49// AppiumBy.accessibilityId("Search Wikipedia")));50// searchElement.click();51// WebElement insertTextElement = (WebElement) new WebDriverWait(driver, 30).until(52// ExpectedConditions.elementToBeClickable(53// AppiumBy.id("org.wikipedia.alpha:id/search_src_text")));54// insertTextElement.sendKeys("BrowserStack");55// Thread.sleep(5000);56//// List<WebElement> allProductsName = driver.findElementsByClassName(57//// "android.widget.TextView");58//// assert(allProductsName.size() > 0);59//60//61// // Invoke driver.quit() after the test is done to indicate that the test is completed.62// driver.quit();63//64// }65//}...
AppiumBy
Using AI Code Generation
1package com.appium;2import io.appium.java_client.AppiumDriver;3import io.appium.java_client.MobileElement;4import io.appium.java_client.android.AndroidDriver;5import io.appium.java_client.android.AndroidKeyCode;6import io.appium.java_client.pagefactory.AppiumFieldDecorator;7import io.appium.java_client.service.local.AppiumDriverLocalService;8import io.appium.java_client.service.local.AppiumServiceBuilder;9import io.appium.java_client.service.local.flags.GeneralServerFlag;
AppiumBy
Using AI Code Generation
1import io.appium.java_client.AppiumBy;2import io.appium.java_client.MobileBy;3import io.appium.java_client.MobileElement;4import io.appium.java_client.android.AndroidDriver;5import java.io.File;6import java.net.MalformedURLException;7import java.net.URL;8import org.openqa.selenium.By;9import org.openqa.selenium.remote.DesiredCapabilities;10public class AppiumByClass {11public static void main(String[] args) throws MalformedURLException, InterruptedException {12File appDir = new File("src");13File app = new File(appDir, "ApiDemos-debug.apk");14DesiredCapabilities capabilities = new DesiredCapabilities();15capabilities.setCapability("deviceName","Android Emulator");16capabilities.setCapability("app", app.getAbsolutePath());
AppiumBy
Using AI Code Generation
1By by = AppiumBy.AccessibilityId("Accessibility");2driver.findElement(by).click();3By by = MobileBy.AccessibilityId("Accessibility");4driver.findElement(by).click();5By by = AndroidBy.AccessibilityId("Accessibility");6driver.findElement(by).click();7By by = IOSBy.AccessibilityId("Accessibility");8driver.findElement(by).click();9By by = WindowsBy.AccessibilityId("Accessibility");10driver.findElement(by).click();11By by = By.AccessibilityId("Accessibility");12driver.findElement(by).click();13By by = MobileBy.AccessibilityId("Accessibility");14driver.findElement(by).click();15By by = AndroidBy.AccessibilityId("Accessibility");16driver.findElement(by).click();17By by = IOSBy.AccessibilityId("Accessibility");18driver.findElement(by).click();19By by = WindowsBy.AccessibilityId("Accessibility");20driver.findElement(by).click();21By by = By.AccessibilityId("Accessibility");22driver.findElement(by).click();23By by = MobileBy.AccessibilityId("Accessibility");24driver.findElement(by).click();25By by = AndroidBy.AccessibilityId("Accessibility");26driver.findElement(by).click();
AppiumBy
Using AI Code Generation
1WebElement element = driver.findElement(AppiumBy.id("com.android.calculator2:id/digit_1"));2WebElement element = driver.findElement(AppiumBy.AccessibilityId("Accessibility"));3WebElement element = driver.findElement(AppiumBy.name("Accessibility"));4WebElement element = driver.findElement(AppiumBy.className("android.widget.TextView"));5WebElement element = driver.findElement(AppiumBy.tagName("android.widget.TextView"));6WebElement element = driver.findElement(AppiumBy.cssSelector("android.widget.TextView"));7WebElement element = driver.findElement(AppiumBy.linkText("Accessibility"));8WebElement element = driver.findElement(AppiumBy.partialLinkText("Access"));9WebElement element = driver.findElement(AppiumBy.AndroidUIAutomator("new UiSelector().text(\"Accessibility\")"));10WebElement element = driver.findElement(AppiumBy.iOSUIAutomation(".elements()[0].cells()[0]"));11WebElement element = driver.findElement(AppiumBy.WindowsUIAutomation("new UiSelector().text(\"Accessibility\")"));12File file = new File("C:\\Users\\username\\Downloads\\Image.png");13WebElement element = driver.findElement(AppiumBy.image(file));14WebElement element = driver.findElement(AppiumBy.custom("some custom locator", "some custom locator value", "some custom locator value"));15WebElement element = driver.findElement(AppiumBy.custom("some custom locator", "some custom locator value", "some custom locator value", "some custom locator value"));16WebElement element = driver.findElement(App
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!