How to start appium test on iOS simulator? - ios

I have the following setup and trying to start the test on iOS Simulator. I am a beginner and don't know how to start the test. I have already imported and installed appium from tutorials.
The questions are:
Is this setup correct?
How to run the tests?
import java.io.File;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
public class AppiumDriver {
private static final String JavascriptExecutor = null;
public WebDriver driver = null;
#BeforeMethod
public void setUp() throws Exception {
// set up appium
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability(CapabilityType.BROWSER_NAME, "iOS");
capabilities.setCapability(CapabilityType.VERSION, "8.1");
capabilities.setCapability(CapabilityType.PLATFORM, "Mac");
capabilities.setCapability("device", "iPhone");
capabilities.setCapability("app", "path here, i have started it with appium inspector and it works");
driver = new RemoteWebDriver(new URL("http://127.0.0.1:4725/wd/hub"), capabilities);
System.out.println("App launched");
}
#Test
public void test01() throws InterruptedException {
driver.findElement(By.name("Guest")).click();
Thread.sleep(5000);
}
#AfterMethod
public void tearDown() throws Exception {
driver.quit();
}
}

Yes, your setup is correct. Looks like you are using testng framework so just run it as "testng" and you should be good to go.

Related

Appium parallel test threadlocal

I am trying to run parallel test through selenium grid.
I know I have to use "thread local" for parallel execution,
but I have a problem with my code.
Cannot invoke "io.appium.java_client.android.AndroidDriver.findElementByAccessibilityId(String)" because "driver" is null
can you please solve it
package appiumset;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Parameters;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.AndroidMobileCapabilityType;
import io.appium.java_client.remote.MobileCapabilityType;
public class _2_Deviceinfo {
public ThreadLocal<AppiumDriver> driver = new ThreadLocal<>();
public void setDriver(AppiumDriver driver) {
this.driver.set(driver);
}
public AppiumDriver getDriver() {
return this.driver.get();
}
#Parameters({"device", "apppackage", "activity","version","appiumServer" , "systemPort", "platformName"})
#BeforeMethod
public synchronized void deviceSetUp(String device, String apppackage, String activity, String version, String appiumServer, String systemPort, String platformName) throws InterruptedException, MalformedURLException {
System.out.println("****************************************");
System.out.println("Setting up device and desired capabilities");
DesiredCapabilities cap = new DesiredCapabilities();
URL url = new URL(appiumServer);
setDriver(new AndroidDriver<>(url, cap));
cap.setCapability(MobileCapabilityType.DEVICE_NAME, device);
cap.setCapability(MobileCapabilityType.UDID, device);
cap.setCapability(AndroidMobileCapabilityType.SYSTEM_PORT, systemPort);
cap.setCapability(MobileCapabilityType.NEW_COMMAND_TIMEOUT, 120);
cap.setCapability(MobileCapabilityType.PLATFORM_NAME, platformName);
//cap.setCapability(MobileCapabilityType., BrowserType.ANDROID);
cap.setCapability(MobileCapabilityType.PLATFORM_VERSION, version);
cap.setCapability(AndroidMobileCapabilityType.APP_PACKAGE, apppackage);
cap.setCapability(AndroidMobileCapabilityType.APP_ACTIVITY, activity);
cap.setCapability("automationName", "UiAutomator2");
cap.setCapability("noReset","false");
cap.setCapability("FullReset","true");
cap.setCapability("APP_WAIT_ACTIVITY", "*");
cap.setCapability("autowebview","false");
}
#AfterMethod
public void closeDriver() {
getDriver().quit();
}
}
I can't find the driver (AppiumDriver)
package appiumset;
import java.net.MalformedURLException;
import java.util.concurrent.TimeUnit;
import org.testng.annotations.Test;
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
public class _3_Onboarding extends _1_Appstart {
#Test
public void onboarding() throws MalformedURLException, InterruptedException {
System.out.println("_3_Onboarding Start");
MobileElement arrow = driver.findElementByAccessibilityId("next");
arrow.click();
System.out.println("next-done");
}
}
call getdriver() method of your class _2_Deviceinfo to your test class.
Appiumdriver<?> driver = getDriver();
MobileElement arrow = driver.findElementByAccessibilityId("next");
arrow.click();

Cannot invoke "io.appium.java_client.android.AndroidDriver.manage()" because "this.driver" is null

I am new to Appium and just getting started, I would like to call methods from other classes by creating an object. but when I call methods it show "this.driver" is null. how to call methods from other class by creating object?? is it possible?? Noted that: I already use 'extends class', so I didn't use it in multiple classes.
//Here, I call methods from other classes......
import java.net.MalformedURLException;
import java.time.Duration;
import java.util.List;
import java.util.NoSuchElementException;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.Dimension;
//import org.openqa.selenium.NoSuchElementException;
import org.openqa.selenium.Point;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.interactions.touch.TouchActions;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.android.nativekey.AndroidKey;
import io.appium.java_client.android.nativekey.KeyEvent;
import io.appium.java_client.MobileBy;
import io.appium.java_client.MobileElement;
import io.appium.java_client.TouchAction;
import static io.appium.java_client.touch.LongPressOptions.longPressOptions;
import static java.time.Duration.ofSeconds;
import io.appium.java_client.touch.LongPressOptions;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
#Test(priority = 11)
public void IncompleteTask() {
String ser="Update For Testing";
Searching(ser);
AllMethods scr=new AllMethods(driver);
scr.Scroll();
//Scroll();
Point point1=driver.findElementByXPath("//android.widget.TextView[#text='Update For Testing']").getCenter();
Point point2=driver.findElementByXPath("//android.widget.TextView[#text='Update For Testing']").getLocation();
Swipping(point1,point2);
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/ll_reAssign").click();
//driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/noButton").click();
String mass=driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/tvMessage").getText();
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/yesButton").click();
String mText="Are you sure you want to undo this Task?";
if(mass.contains(mText))
{
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/yesButton").click();
}
System.out.println("IncompleteTask Executed!");
driver.quit();
}
//Here is my allMethods class
import java.time.Duration;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.Dimension;
import org.openqa.selenium.support.PageFactory;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import java.io.IOException;
import java.lang.NullPointerException;
public class AllMethods {
public AndroidDriver<AndroidElement> driver;
public AllMethods(AndroidDriver driver)
{
PageFactory.initElements(driver, this);
}
public void searching(String ser) {
driver.findElementById("bd.com.cslsoft.kandareeliteapp:id/ll_search").click();
driver.findElementById("android:id/search_src_text").sendKeys(ser);
driver.hideKeyboard();
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
public void Scroll() throws NullPointerException
{
for(int i=0; i<3; i++)
{
Dimension dimension=driver.manage().window().getSize();
int start_x=(int) (dimension.width*0.5);
int start_y=(int) (dimension.height*0.2);
int end_x=(int) (dimension.width*0.5);
int end_y=(int) (dimension.height*0.8);
TouchAction tcD=new TouchAction(driver);
tcD.press(PointOption.point(start_x,
start_y)).waitAction(WaitOptions.waitOptions(Duration.ofSeconds(2)))
.moveTo(PointOption.point(end_x, end_y)).release().perform();
}
}
}
The methods in AllMethods class are referring to the driver which is not yet initialized. i.e they are referring to this driver :
public AndroidDriver<AndroidElement> driver;
You will need to add this.driver=driver inside AllMethods constructor, this will set the driver with the reference of the driver that is passed in the constructor.

How to test AuthenticationPrincipal and getting an ID Token in Spring Security?

I have the following LogoutResource class that returns an ID Token.
package com.mycompany.myapp.web.rest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.client.registration.ClientRegistration;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
/**
* REST controller for managing global OIDC logout.
*/
#RestController
public class LogoutResource {
private ClientRegistration registration;
public LogoutResource(ClientRegistrationRepository registrations) {
this.registration = registrations.findByRegistrationId("oidc");
}
/**
* {#code POST /api/logout} : logout the current user.
*
* #param request the {#link HttpServletRequest}.
* #param idToken the ID token.
* #return the {#link ResponseEntity} with status {#code 200 (OK)} and a body with a global logout URL and ID token.
*/
#PostMapping("/api/logout")
public ResponseEntity<?> logout(HttpServletRequest request,
#AuthenticationPrincipal(expression = "idToken") OidcIdToken idToken) {
String logoutUrl = this.registration.getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
Map<String, String> logoutDetails = new HashMap<>();
logoutDetails.put("logoutUrl", logoutUrl);
logoutDetails.put("idToken", idToken.getTokenValue());
request.getSession().invalidate();
return ResponseEntity.ok().body(logoutDetails);
}
}
This works, but I'd like to test it. I tried the following:
package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.JhipsterApp;
import com.mycompany.myapp.config.Constants;
import com.mycompany.myapp.security.AuthoritiesConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.Ignore;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.oauth2.core.user.DefaultOAuth2User;
import org.springframework.security.oauth2.core.user.OAuth2User;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAmount;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.security.test.web.servlet.request.SecurityMockMvcRequestPostProcessors.authentication;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {#link LogoutResource} REST controller.
*/
#RunWith(SpringRunner.class)
#SpringBootTest(classes = JhipsterApp.class)
public class LogoutResourceIT {
#Autowired
private ClientRegistrationRepository registrations;
#Autowired
private MappingJackson2HttpMessageConverter jacksonMessageConverter;
private final static String ID_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsIm" +
"p0aSI6ImQzNWRmMTRkLTA5ZjYtNDhmZi04YTkzLTdjNmYwMzM5MzE1OSIsImlhdCI6MTU0M" +
"Tk3MTU4MywiZXhwIjoxNTQxOTc1MTgzfQ.QaQOarmV8xEUYV7yvWzX3cUE_4W1luMcWCwpr" +
"oqqUrg";
private MockMvc restLogoutMockMvc;
#Before
public void before() {
LogoutResource logoutResource = new LogoutResource(registrations);
this.restLogoutMockMvc = MockMvcBuilders.standaloneSetup(logoutResource)
.setMessageConverters(jacksonMessageConverter).build();
}
#Test
public void getLogoutInformation() throws Exception {
Map<String, Object> claims = new HashMap<>();
claims.put("groups", "ROLE_USER");
claims.put("sub", 123);
OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
Instant.now().plusSeconds(60), claims);
String logoutUrl = this.registrations.findByRegistrationId("oidc").getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
restLogoutMockMvc.perform(post("/api/logout")
.with(authentication(createMockOAuth2AuthenticationToken(idToken))))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.logoutUrl").value(logoutUrl));
}
private OAuth2AuthenticationToken createMockOAuth2AuthenticationToken(OidcIdToken idToken) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
OidcUser user = new DefaultOidcUser(authorities, idToken);
return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
}
However, this results in the following error:
Caused by: java.lang.IllegalArgumentException: tokenValue cannot be empty
at org.springframework.util.Assert.hasText(Assert.java:284)
at org.springframework.security.oauth2.core.AbstractOAuth2Token.<init>(AbstractOAuth2Token.java:55)
at org.springframework.security.oauth2.core.oidc.OidcIdToken.<init>(OidcIdToken.java:53)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at java.base/jdk.internal.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at java.base/jdk.internal.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.base/java.lang.reflect.Constructor.newInstance(Constructor.java:490)
at org.springframework.beans.BeanUtils.instantiateClass(BeanUtils.java:172)
Does anyone know of a way to mock AuthenticationPrincipal and have it return a preset ID token?
Answer provided by Joe Grandja from the Spring Security Team:
The AuthenticationPrincipalArgumentResolver is not getting registered in your test.
NOTE: It automatically gets registered when the "full" spring-web-mvc is enabled, e.g #EnableWebMvc
However, in your #Before, you have:
MockMvcBuilders.standaloneSetup() - this does not initialize the full web-mvc infrastructure - only a subset
Try this instead:
MockMvcBuilders.webAppContextSetup(this.context) - this will register AuthenticationPrincipalArgumentResolver and your test should resolve the OidcIdToken.
I changed my test to the following and now everything passes. Thanks Joe!
package com.mycompany.myapp.web.rest;
import com.mycompany.myapp.JhipsterApp;
import com.mycompany.myapp.security.AuthoritiesConstants;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.client.authentication.OAuth2AuthenticationToken;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.core.oidc.OidcIdToken;
import org.springframework.security.oauth2.core.oidc.user.DefaultOidcUser;
import org.springframework.security.oauth2.core.oidc.user.OidcUser;
import org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
/**
* Integration tests for the {#link LogoutResource} REST controller.
*/
#RunWith(SpringRunner.class)
#SpringBootTest(classes = JhipsterApp.class)
public class LogoutResourceIT {
#Autowired
private ClientRegistrationRepository registrations;
#Autowired
private WebApplicationContext context;
private final static String ID_TOKEN = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9" +
".eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiYWRtaW4iOnRydWUsIm" +
"p0aSI6ImQzNWRmMTRkLTA5ZjYtNDhmZi04YTkzLTdjNmYwMzM5MzE1OSIsImlhdCI6MTU0M" +
"Tk3MTU4MywiZXhwIjoxNTQxOTc1MTgzfQ.QaQOarmV8xEUYV7yvWzX3cUE_4W1luMcWCwpr" +
"oqqUrg";
private MockMvc restLogoutMockMvc;
#Before
public void before() throws Exception {
Map<String, Object> claims = new HashMap<>();
claims.put("groups", "ROLE_USER");
claims.put("sub", 123);
OidcIdToken idToken = new OidcIdToken(ID_TOKEN, Instant.now(),
Instant.now().plusSeconds(60), claims);
SecurityContextHolder.getContext().setAuthentication(authenticationToken(idToken));
SecurityContextHolderAwareRequestFilter authInjector = new SecurityContextHolderAwareRequestFilter();
authInjector.afterPropertiesSet();
this.restLogoutMockMvc = MockMvcBuilders.webAppContextSetup(this.context).build();
}
#Test
public void getLogoutInformation() throws Exception {
String logoutUrl = this.registrations.findByRegistrationId("oidc").getProviderDetails()
.getConfigurationMetadata().get("end_session_endpoint").toString();
restLogoutMockMvc.perform(post("/api/logout"))
.andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_UTF8_VALUE))
.andExpect(jsonPath("$.logoutUrl").value(logoutUrl))
.andExpect(jsonPath("$.idToken").value(ID_TOKEN));
}
private OAuth2AuthenticationToken authenticationToken(OidcIdToken idToken) {
Collection<GrantedAuthority> authorities = new ArrayList<>();
authorities.add(new SimpleGrantedAuthority(AuthoritiesConstants.USER));
OidcUser user = new DefaultOidcUser(authorities, idToken);
return new OAuth2AuthenticationToken(user, authorities, "oidc");
}
}

How can i launch an iOS app which installed already using appium

In order to test the duplication in registering,I need to close and relaunch the iOS application.Can any one provide the best and simple scripts to close an application and relaunch the same in iOS using Appium and JAVA?
You can achieve the following way :
import io.appium.java_client.AppiumDriver;
import io.appium.java_client.MobileElement;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
public class SampleTest {
AppiumDriver<?> appiumDriver;
final String URL_STRING = "http://127.0.0.1:4723/wd/hub";
URL url = new URL(URL_STRING);
public SampleTest() throws MalformedURLException {
}
#BeforeTest
public void beforeTest() {
File appDir = new File("path to ipa file");
File app = new File(appDir, "app.ipa");
DesiredCapabilities iOSCapabilities = new DesiredCapabilities();
iOSCapabilities.setCapability(MobileCapabilityType.PLATFORM, "iOS");
iOSCapabilities.setCapability(MobileCapabilityType.AUTOMATION_NAME, "XCUITest");
iOSCapabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "iPhone6s");
iOSCapabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "11.2.1");
iOSCapabilities.setCapability(MobileCapabilityType.UDID, "udid");
iOSCapabilities.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
appiumDriver = new IOSDriver(url, iOSCapabilities);
}
#Test
public void test() {
//perform some test
}
#AfterTest
public void afterTest() {
// following command will close and restart the app
appiumDriver.resetApp();
}
}
You may want to check this for more details.
use the driver driver.resetApp(), like this
try{
LOG.debug("reset app");
driver.resetApp();
} catch (WebDriverException e){
LOG.error("ERROR on reset app, e: ",e);
}
Appium allows you to start any pre-installed app on the device, so you can use closeApp first and then launchApp with your app bundle id:
// closing app
driver.closeApp();
// launch app again
HashMap<String, Object> args = new HashMap<>();
args.put("bundleId", APP_BUNDLE_ID);
driver.executeScript("mobile: launchApp", args);

I want to scroll down to Specific element using appium in Android, java client v-5.0.4 and appium v-1.7.1

I am trying to scroll down to an element, looked and searched everywhere and no code is helping to scroll down, i have tried with the code below which seems to be not working, anyone gives me the solution to scroll down perfectly.
As swipe and scrollTo functions are depreciated in the latest java client version, a perfect code will help me to solve my TASK
package mobileapp.com.example;
import java.net.MalformedURLException;
import java.net.URL;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.pagefactory.AndroidFindBy;
public class Day5 {
AndroidDriver<WebElement> driver;
#AndroidFindBy (uiAutomator = "new UiScrollable(new UiSelector()).scrollIntoView(new UiSelector().textContains(\"PHP\"))")
public WebElement scrollStepOne;
#BeforeTest
public void setup() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("BROWSER_NAME", "Android");
capabilities.setCapability("VERSION", "6.0.1");
capabilities.setCapability("deviceName","Nexus 5");
capabilities.setCapability("platformName","Android");
capabilities.setCapability("appPackage", "com.vector.guru99");
capabilities.setCapability("appActivity","com.vector.guru99.BaseActivity");
driver= new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
#Test
public void StartTest() throws InterruptedException {
//Verify Homepage
if(driver.findElement(By.id("android:id/action_bar_title")).isDisplayed())
System.out.println("Home page is displayed");
else
System.out.println("Home page is not displayed");
//step2 - click on Course List tab
driver.findElement(By.name("Course List")).click();
System.out.println("Courses list are : ");
Thread.sleep(3000);
//Step 3 - darg until PHP course found and click on it
scrollStepOne.click();
Thread.sleep(3000);
// driver.findElement(By.xpath("//android.widget.TextView[#text()='PHP']")).click();
// Thread.sleep(3333);
//Step 4 - Click on lesson 1 and verify
driver.findElement(By.xpath("//android.widget.TextView[#text='What is PHP? Write your first PHP Program']")).click();
Thread.sleep(3333);
if(driver.findElement(By.id("com.vector.guru99:id/lesson_title")).isDisplayed())
System.out.println("First Lesson is displayed");
else
System.out.println("First lesson not opened");
}
#AfterTest
public void tearDown() {
driver.quit();
}
}
for scrolling to a element have a text as App_Settings, you can use the below
androidDriver.findElementByAndroidUIAutomator("new UiScrollable(new UiSelector().scrollable(true).instance(0))" +
".scrollIntoView(new UiSelector().description(\"App_Settings\"));");

Resources