Trước hết để có thể sử dụng tính năng này bạn cần sử dụng thư viện Appium của java như dưới đây :
Code: Select all
<dependency>
<groupId>com.github.appium</groupId>
<artifactId>java-client</artifactId>
<version>969fac6a1c6dd229bdefb02ff10e71c812701e0c</version>
</dependency>
Và dưới đây là đoạn code ví dụ:
Code: Select all
public class FindByImage {
private String APP_IOS = "https://github.com/cloudgrey-io/the-app/releases/download/v1.7.0/TheApp-v1.7.0.app.zip";
private String APP_ANDROID = "https://github.com/cloudgrey-io/the-app/releases/download/v1.7.0/TheApp-v1.7.0.apk";
private static By photos = MobileBy.AccessibilityId("Photo Demo");
@Test
public void testImage_iOS() throws URISyntaxException, IOException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "iOS");
capabilities.setCapability("platformVersion", "12.0");
capabilities.setCapability("deviceName", "iPhone X");
capabilities.setCapability("app", APP_IOS);
IOSDriver driver = new IOSDriver<>(new URL("http://localhost:4723/wd/hub"), capabilities);
actualTest(driver);
}
@Test
public void testImage_Android() throws URISyntaxException, IOException {
DesiredCapabilities capabilities = new DesiredCapabilities();
capabilities.setCapability("platformName", "Android");
capabilities.setCapability("deviceName", "Android Emulator");
capabilities.setCapability("automationName", "UiAutomator2");
capabilities.setCapability("app", APP_ANDROID);
AndroidDriver driver = new AndroidDriver(new URL("http://localhost:4723/wd/hub"), capabilities);
actualTest(driver);
}
private String getReferenceImageB64() throws URISyntaxException, IOException {
URL refImgUrl = getClass().getClassLoader().getResource("Reference_Image.png");
File refImgFile = Paths.get(refImgUrl.toURI()).toFile();
return Base64.getEncoder().encodeToString(Files.readAllBytes(refImgFile.toPath()));
}
public void actualTest(AppiumDriver driver) throws URISyntaxException, IOException {
WebDriverWait wait = new WebDriverWait(driver, 10);
try {
// get to the photo view
wait.until(ExpectedConditions.presenceOfElementLocated(photos)).click();
// wait for and click the correct image using a reference image template
By sunriseImage = MobileBy.image(getReferenceImageB64());
wait.until(ExpectedConditions.presenceOfElementLocated(sunriseImage)).click();
// verify that the resulting alert proves we clicked the right image
wait.until(ExpectedConditions.alertIsPresent());
String alertText = driver.switchTo().alert().getText();
Assert.assertEquals(alertText, Matchers.containsString("sunrise"));
} finally {
driver.quit();
}
}
}