处理Toast
Toast是Android中用来显示信息的一种机制,和Dialog不一样,它没有焦点,而且显示的时间有限,很快就消失,Toast是Android的系统特性,不是应用特性,因此通过UI Automator Viewer无法获取控件
图片对比
Toast被触发后,截图对比
WebElement imagebtn = driver.findElementById("ShowToastButton");
imagebtn.click();
try{
// 通过getScreenshotAs方法来捕捉屏幕,使用OutputType.File作为参数传递给getScreenshotAs方法
// 告诉它将截取的屏幕以文件的形式返回
File scrFile = driver.getScreenshotAs(OutpuType.File);
// 使用copyFile保存getScreenshotAs截取的屏幕文件到D盘中并命名为scrshot.png
FileUtils.copyFile(scrFile, new File("D:\\scrshot.png"));
}catch(Exception e){
e.printStackTrace();
}
Selendroid方法
Selendroid方法(自动化测试引擎)可以识别Toast控件,采用WaitForElement方法获得Toast文本
waitForElement(By.partialLinkText("Hello seledroid toast"), 4, driver);
Automator2
在新版本的Appium中,使用Automator2自动化测试引擎,可以获取Toast
package org.davieyang.testscripts;
import static org.testng.Assert.assertNotNull;
import io.appium.java_client.android.Activity;
import io.appium.java_client.android.AndroidDriver;
import java.io.File;
import java.net.URL;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import io.appium.java_client.remote.AutomationName;
import io.appium.java_client.remote.MobileCapabilityType;
public class ToastDemo {
AndroidDriver<WebElement> driver;
@BeforeMethod
public void setUp()throws Exception{
File appDir = new File("D:\\");
File app = new File(appDir, "selendroid-test-app-0.17.0.apk");
DesiredCapabilities cap = new DesiredCapabilities();
cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Android Emulator");
cap.setCapability(MobileCapabilityType.APP, app.getAbsolutePath());
cap.setCapability(MobileCapabilityType.AUTOMATION_NAME, AutomationName.ANDROID_UIAUTOMATOR2);
driver = new AndroidDriver<>(new URL("http://127.0.0.1:4723/wd/hub"), cap);
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testToast(){
Activity activity = new Activity("io.selendroid.testapp", ".HomeScreenActivity");
driver.startActivity(activity);
WebElement toastButton = null;
toastButton = driver.findElement(By.id("io.selendroid.testapp:id/showToastButton"));
toastButton.click();
final WebDriverWait wait = new WebDriverWait(driver, 10);
assertNotNull(wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath("//*[@text='Hello selendroid toast!']"))));
}
@AfterMethod
public void TearDown(){
driver.quit();
}
}