Appium 2.0结合TestNG时If-else逻辑未按预期执行
问题根源
driver.findElement()方法在找不到目标元素时,不会返回null,而是直接抛出NoSuchElementException异常,这会导致代码直接中断执行,根本没有机会进入else分支。
解决方案
以下两种方法可以解决这个问题:
方法1:使用findElements()判断元素是否存在
findElements()找不到元素时会返回空列表,不会抛出异常,因此可以先通过列表长度判断元素是否存在,再检查显示状态:
List<WebElement> targetElements = driver.findElements(AppiumBy.accessibilityId("___")); if (!targetElements.isEmpty() && targetElements.get(0).isDisplayed()) { driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"OK\"]")).click(); driver.findElement(AppiumBy.xpath("//XCUIElementTypeButton[@name=\"menu_edit\"]")).click(); driver.findElement(AppiumBy.accessibilityId("Locations")).click(); driver.findElement(AppiumBy.accessibilityId("0")).click(); deleteLocation(); driver.findElement(AppiumBy.accessibilityId("cancel_dm")).click(); driver.findElement(AppiumBy.accessibilityId("userProfile")).click(); driver.findElement(AppiumBy.xpath("//XCUIElementTypeButton[@name=\"Delete Account\"]")).click(); driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"YES\"]")).click(); Thread.sleep(3000); driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"OK\"]")).click(); } else { driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"OK\"]")).click(); }
方法2:捕获NoSuchElementException异常
将元素定位逻辑放入try-catch块,捕获找不到元素的异常后执行else分支的逻辑:
try { WebElement targetElement = driver.findElement(AppiumBy.accessibilityId("___")); if (targetElement.isDisplayed()) { driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"OK\"]")).click(); driver.findElement(AppiumBy.xpath("//XCUIElementTypeButton[@name=\"menu_edit\"]")).click(); driver.findElement(AppiumBy.accessibilityId("Locations")).click(); driver.findElement(AppiumBy.accessibilityId("0")).click(); deleteLocation(); driver.findElement(AppiumBy.accessibilityId("cancel_dm")).click(); driver.findElement(AppiumBy.accessibilityId("userProfile")).click(); driver.findElement(AppiumBy.xpath("//XCUIElementTypeButton[@name=\"Delete Account\"]")).click(); driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"YES\"]")).click(); Thread.sleep(3000); driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"OK\"]")).click(); } } catch (NoSuchElementException e) { driver.findElement(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"OK\"]")).click(); }
额外优化建议
- 避免使用
Thread.sleep(),改用WebDriverWait显式等待提升代码稳定性:WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(10)); wait.until(ExpectedConditions.elementToBeClickable(AppiumBy.xpath("//XCUIElementTypeStaticText[@name=\"OK\"]"))).click(); - 重复定位的元素(如OK按钮)可以封装成单独方法,减少代码冗余。
内容的提问来源于stack exchange,提问作者Sandesh Rathod
相关产品推荐
相关产品推荐

