工具类封装
package com.ideal.base;
import io.appium.java_client.functions.ExpectedCondition;
import io.appium.java_client.touch.WaitOptions;
import io.appium.java_client.touch.offset.PointOption;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Date;
import java.util.List;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
import org.checkerframework.checker.nullness.compatqual.NullableDecl;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import java.net.MalformedURLException;
import java.net.URL;
import io.appium.java_client.TouchAction;
import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
public class BaseAppium {
//调试设备名字
public static String deviceName = "192.168.3.159:5555";
//设备名称.
public static String platformName = "Android";
//包名
public static String appPackage = "com.tydic.phone.tray.experience";
//类名
public static String appActivity = "com.tydic.phone.tray.activity.MainActivity";
//是否需要重新安装
public static String noReset = "True";
//调试设备系统版本
public static String platformVersion = "4.4.2";
//是否不重新签名
public static String noSign = "True";
//是否使用unicode输入法,真是支持中文
public static String unicodeKeyboard = "True";
//元素定位的id
public static String finalId = appPackage + ":id/";
//用户名
public static String userName = "gejm";
//密码
public static String passWord = "`135qetu";
public static AndroidDriver<AndroidElement> driver = null;
/**
* appium启动参数
*/
@BeforeSuite
public void beforeSuite() throws MalformedURLException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("deviceName", deviceName);
capabilities.setCapability("appPackage", appPackage);
capabilities.setCapability("platformName", platformName);
//支持中文
capabilities.setCapability("unicodeKeyboard", unicodeKeyboard);
//不重复安装
capabilities.setCapability("noReset", noReset);
//不重新签名
capabilities.setCapability("noSign", noSign);
//打开的activity
capabilities.setCapability("appActivity", appActivity);
//启动Driver
driver = new AndroidDriver<>(
new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
}
@AfterTest
public void afterTest() {
//结束这次测试
driver.quit();
}
/*
* 用户名
*/
public static void sendName(String id) {
getElement(By.id(finalId + id)).sendKeys(userName);
}
/*
* 密码
*/
public static void sendPwd(String id) {
getElement(By.id(finalId + id)).sendKeys(passWord);
System.out.println(passWord);
}
//智能等待:在规定的时间内会去尝试多次定位元素,如果在规定的时间内找不到的话,那么会抛出超时异常
//显示等待
static By by;
public static WebElement getElement(By by) {
WebDriverWait webDriverWait = new WebDriverWait(driver, 30);
WebElement webElement = webDriverWait.until(new ExpectedCondition<WebElement>() {
@NullableDecl
@Override
public WebElement apply(@NullableDecl WebDriver input) {
return driver.findElement(by);
}
});
return webElement;
}
/*
* id---根据id定位元素的点击事件
*/
public static void clickById(String id) {
getElement(By.id(finalId + id)).click();
}
/*
* id---根据id定位元素清除文本框
*/
public static void cleanById(String id) {
getElement(By.id(finalId + id)).clear();
}
/*
* 输入值
*/
public static void sendKeys(String id, String key) {
getElement(By.id(finalId + id)).sendKeys(key);
}
/*
* enter回车键.
*/
public static void hide() {
driver.pressKeyCode(66);
}
/*
* 判断元素是否存在
*/
public static boolean byElementIsExist(String id) {
try {
getElement(By.id(finalId + id));
return true;
} catch (Exception e) {
return false;
}
}
/***
* xpath根据content-desc查找元素
*
* @param view的类型
* @param content-desc
* 的内容
* @return
*/
public WebElement getViewbyXathwithcontentdesc(String view, String name) {
return driver.findElementByXPath("//" + view + "[contains(@content-desc,'" + name + "')]");
}
/***
* xpath根据text查找元素
*
* @param view的类型
* @param text的内容
* @return
*/
public WebElement getViewbyXathwithtext(String view, String name) {
return driver.findElementByXPath("//" + view + "[contains(@text,'" + name + "')]");
}
/***
* 根据UIautomator底层方法得到对应desc的view
*
* @param desc名
* @return View
*/
public WebElement getViewbyUidesc(String name) {
return driver
.findElementByAndroidUIAutomator("new UiSelector().descriptionContains(\"" + name + "\")");
}
/***
* 根据UIautomator底层方法得到对应text的view
*
* @param text名
* @return View
*/
public WebElement getViewbyUitext(String name) {
return driver
.findElementByAndroidUIAutomator("new UiSelector().textContains(\"" + name + "\")");
}
/*
* xpath---点击事件
*/
public static void clickByXpath(String xpath) {
getElement(By.xpath(xpath)).click();
}
/*
* name---点击事件
*/
public static void clickByName(By by, String name) {
getElement(By.name(name)).click();
}
/*
* 根据xpath---获取文本信息
*/
public static String getTextByXpath(String xpath) {
String text = getElement(By.xpath(xpath)).getText();
return text;
}
/*
* 点击事件封装
*/
public static void clickBy(By by) {
driver.findElement(by).click();
}
/*
* 根据element获取文本信息
*/
public static String getText(By by) {
String text = driver.findElement(by).getText();
return text;
}
/*
* 封装断言
* actual 实际值
* expected 期望值
* string 返回的断言信息
*/
static boolean flog = true;
public static void verifyassert(Object actual, Object expected, String string) {
try {
Assert.assertEquals(string, actual, expected);
} catch (Error e) {
flog = false;
}
}
/**
* 线程休眠秒数,单位秒
*
* @param s 要休眠的秒数
*/
public void sleep(long s) throws InterruptedException {
Thread.sleep(s);
}
/**
* 获取当前界面的所有EditText,并依次输入内容
*
* @param str 要输入的数组
*/
public void inputManyText(String[] str) {
List<AndroidElement> textFieldsList = driver.findElementsByClassName("android.widget.EditText");
for (int i = 0; i < str.length; i++) {
textFieldsList.get(i).sendKeys(str[i]);
}
}
/*
* 输出当前类名
*/
public String printActivity() {
String activi = driver.currentActivity();
return activi;
}
/*
* 验证activity
*/
public boolean verifyActivity(String activity) {
if (driver.currentActivity().equals(activity)) {
return true;
}
return false;
}
// index
public static void clickByIndex(By by, Integer index) {
List<AndroidElement> list = driver.findElements(by);
WebElement targetEle = list.get(index);
targetEle.click();
}
public static void sendKeysByIndex(By by, int index, String string) {
List<AndroidElement> lis = driver.findElements(by);
WebElement targetEle = lis.get(index);
targetEle.sendKeys(string);
}
public static void click(By by, int index) {
List<AndroidElement> lis = driver.findElements(by);
WebElement targetEle = lis.get(index);
targetEle.click();
}
public static void sendKeys(By by, int index, String string) {
List<AndroidElement> lis = driver.findElements(by);
WebElement targetEle = lis.get(index);
targetEle.sendKeys(string);
}
public static String getText(By by, int index) {
List<AndroidElement> lis = driver.findElements(by);
WebElement targetEle = lis.get(index);
String string = targetEle.getText();
return string;
}
public static List<AndroidElement> getElementsByClassAndIndex(String classname,
int index) {
List<AndroidElement> lis = null;
lis = driver.findElementsByAndroidUIAutomator(
"new UiSelector().className(" + classname + ").index(" + index + ")");
return lis;
}
public static List<AndroidElement> getElementsByClassAndIndexAndClickable(String classname,
int index) {
List<AndroidElement> list = null;
list = driver.findElementsByAndroidUIAutomator(
"new UiSelector().className(" + classname + ").index(" + index + ").clickable(true)");
return list;
}
/*
*屏幕截图
*/
public static void takeScreenShot(AndroidDriver<WebElement> driver) {
File screenShotFile = driver.getScreenshotAs(OutputType.FILE);
try {
FileUtils.copyFile(screenShotFile,
new File("D:\\AutoScreenCapture\\" + getCurrentDateTime() + ".jpg"));
} catch (IOException e) {
e.printStackTrace();
}
}
/*
* 设置日期格式
*/
public static String getCurrentDateTime() {
SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd_HHmmss");
return df.format(new Date());
}
/*
*push文件 上传
*/
public static void pushFile() {
File file = new File("d:\\test.txt"); //test.txt内容为"test"
String content = null;
try {
content = FileUtils.readFileToString(file);
} catch (IOException e) {
e.printStackTrace();
}
byte[] data = Base64.encodeBase64(content.getBytes());
driver.pushFile("sdcard/test.txt", data);
}
/*
* pull文件 下载
*/
public static void pullFile() {
byte[] resultDate = driver.pullFile("sdcard/test.txt");
System.out.println(new String(Base64.decodeBase64(resultDate)));
}
//下载文件夹
public static void pullFolder() {
driver.pullFolder("tmp/");
//把android的tmp目录拷贝到临时文件夹
System.out.println(driver.pullFolder("tmp/"));
}
/*
* 上滑
**/
static Duration duration = Duration.ofSeconds(800);
public static void swipeUp(AndroidDriver driver) {
int width = BaseAppium.driver.manage().window().getSize().width;
int height = BaseAppium.driver.manage().window().getSize().height;
PointOption point1 = PointOption.point(width / 2, height * 4 / 5);
PointOption point2 = PointOption.point(width / 2, height / 4);
WaitOptions waitOptions = WaitOptions.waitOptions(duration);
TouchAction action1 = new TouchAction(BaseAppium.driver).press(point1).waitAction(waitOptions)
.moveTo(point2).release();
action1.perform();
}
/*
*
* 下滑
* */
public static void swipeDown() {// scroll down to refresh
int width = driver.manage().window().getSize().width;
int height = driver.manage().window().getSize().height;
PointOption point1 = PointOption.point(width / 2, height / 4);
PointOption point2 = PointOption.point(width / 2, height * 3 / 4);
WaitOptions waitOptions = WaitOptions.waitOptions(duration);
TouchAction action1 = new TouchAction(driver).press(point1).waitAction(waitOptions)
.moveTo(point2).release();
action1.perform();
}
/*
*
* 左滑
* */
public static void swipeLeft() {
int width = driver.manage().window().getSize().width;
int height = driver.manage().window().getSize().height;
PointOption point1 = PointOption.point(width - 10, height / 2);
PointOption point2 = PointOption.point(width / 4, height / 2);
WaitOptions waitOptions = WaitOptions.waitOptions(duration);
TouchAction action1 = new TouchAction(driver).press(point1).waitAction(waitOptions)
.moveTo(point2).release();
action1.perform();
}
/*
* 右滑
* */
public static void swipeRight() {
int width = driver.manage().window().getSize().width;
int height = driver.manage().window().getSize().height;
PointOption point1 = PointOption.point(10, height / 2);
PointOption point2 = PointOption.point(width * 3 / 4 + 10, height / 2);
WaitOptions waitOptions = WaitOptions.waitOptions(duration);
TouchAction action1 = new TouchAction(driver).press(point1).waitAction(waitOptions)
.moveTo(point2).release();
action1.perform();
}
//页面不断上滑,滑动到出现 THE END为止
public static void swipeToEnd(AndroidDriver driver) {
int width = driver.manage().window().getSize().width;
int height = driver.manage().window().getSize().height;
boolean isSwipe = true;
String endString = "THE END";
while (isSwipe) {
swipeUp(driver);//向上滑动屏幕
String temp = driver.getPageSource();
if (temp.contains(endString)) {
isSwipe = false;
}
}
}
//手势解锁九宫格
/**
* 手势解锁九宫格 0 1 2 3 4 5 6 7 8
*/
public void swipeToUnlock(WebElement lockImageView, int[] path) {
TouchAction touchAction = new TouchAction(driver);
List<WebElement> lockItems = lockImageView.findElements(By.className("android.view.View"));
for (int i = 0; i < path.length; i++) {
if (i == 0) {
touchAction.press((PointOption) lockItems.get(path[i])).moveTo(
(PointOption) lockItems.get(path[i]));
} else {
touchAction.moveTo((PointOption) lockItems.get(path[i]));
}
}
touchAction.release();
touchAction.perform();
}
}
登录demo
package com.ideal.test;
import com.ideal.base.*;
import org.testng.annotations.Test;
public class LoginTest extends BaseAppium{
@Test
public void userLogin() throws Exception {
//点击账号登录
BaseAppium.clickById("account_title");
//输入用户名
BaseAppium.clickById("userName");
//清除文本框
BaseAppium.cleanById("userName");
BaseAppium.sendName("userName");
//输入密码
BaseAppium.clickById("pwd");
BaseAppium.sendPwd("pwd");
BaseAppium.hide();
//点击登录
BaseAppium.clickById("login_btn");
Thread.sleep(3000);
boolean skip = BaseAppium
.byElementIsExist(("btn_net"));
if (skip == true) {
System.out.println("跳过");
BaseAppium.clickById("btn_net");
}
Thread.sleep(3000);
}
}