如何在Selenium TestNG测试中处理Lord&Taylor站点的随机覆盖弹窗
Selenium随机弹窗处理解决方案
核心修复思路
- 解决定位失效问题:放弃动态XPath和精确链接文本定位,改用模糊文本匹配的相对XPath
//*[contains(normalize-space(.), 'DECLINE OFFER')],该定位会匹配所有包含「DECLINE OFFER」文本的元素,不受动态生成的ID、类名、层级变化影响 - 解决随机弹出问题:封装无侵入的弹窗检查方法,设置短时长显式等待,弹窗未加载时直接跳过不抛出异常,在所有涉及Lord & Taylor站点页面操作的步骤前调用该方法即可
- 调整测试执行顺序:将弹窗检查逻辑改为操作前置依赖,避免页面操作测试先执行被弹窗遮挡
优化后代码
package com.LT.Tests; import java.util.concurrent.TimeUnit; import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.chrome.ChromeDriver; import org.openqa.selenium.support.ui.ExpectedConditions; import org.openqa.selenium.support.ui.WebDriverWait; import org.testng.Assert; import org.testng.annotations.AfterTest; import org.testng.annotations.BeforeTest; import org.testng.annotations.Test; import com.LT.Pages.googlePage; import com.LT.Pages.homePage; public class homepageTest { WebDriver driver; googlePage gp; homePage hp; // 弹窗定位器全局复用 private final By declineOfferBtn = By.xpath("//*[contains(normalize-space(.), 'DECLINE OFFER')]"); @BeforeTest public void beforeTest() throws InterruptedException { System.setProperty("webdriver.chrome.driver","/Users/nezamseraj/Desktop/WSA/Drivers/chromedriver 5"); driver = new ChromeDriver(); hp = new homePage(driver); gp = new googlePage(driver); driver.manage().deleteAllCookies(); Thread.sleep(2000); driver.get("https://www.google.com/"); driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS); } // 通用弹窗关闭方法,无弹窗时自动跳过 private void dismissAdIfPresent() { try { new WebDriverWait(driver, 5) .until(ExpectedConditions.elementToBeClickable(declineOfferBtn)) .click(); // 点击后等待弹窗消失 new WebDriverWait(driver, 3) .until(ExpectedConditions.invisibilityOfElementLocated(declineOfferBtn)); } catch (Exception ignored) { // 未检测到弹窗直接跳过,不抛出异常 } } @AfterTest public void afterTest() { driver.quit(); } @Test public void gpValidation() { boolean searchbar = gp.searchBar().isEnabled(); boolean searchbutton = gp.searchbutton().isEnabled(); Assert.assertTrue(searchbar); Assert.assertTrue(searchbutton); } @Test(priority = 2) public void searchLT() { gp.searchBar().sendKeys("Lord and Taylor"); gp.searchbutton().click(); gp.ltLink().click(); // 进入LT站点后先检查一次弹窗 dismissAdIfPresent(); } @Test(priority = 3) public void hpValidation() { // 页面操作前再检查一次弹窗,覆盖延迟弹出场景 dismissAdIfPresent(); boolean ws = hp.womenSection().isEnabled(); boolean ds = hp.designerSection().isEnabled(); boolean as = hp.accessoriesSection().isEnabled(); Assert.assertTrue(ws); Assert.assertTrue(ds); Assert.assertTrue(as); } }
可选优化方案
如果后续弹窗出现场景更多,可以把dismissAdIfPresent()方法封装到页面对象的公共父类中,在所有元素操作方法执行前自动调用,不需要手动在每个测试用例中加调用逻辑。
内容的提问来源于stack exchange,提问作者NS11
相关产品推荐
相关产品推荐

