基于月份文本自动化操作日期选择器时上一步按钮仅点击一次问题
故障根因
- 逻辑层问题:现有
selectStartMonth方法仅用单次if判断是否需要点击上一步,执行1次点击后就直接结束,不会重复校验月份是否匹配目标值 - 元素缓存问题:Selenium PageFactory的
@FindBy注解默认会缓存首次查找到的元素,日历切换月份后页面的月份展示元素文本已经更新,但代码读取的还是首次查找时的缓存值,无法触发后续点击逻辑
修复代码
首先调整月份选择逻辑为循环校验,添加点击次数上限防止死循环,添加等待保证页面渲染完成:
@FindBy(css=".ui-datepicker-month") // 禁用元素缓存,每次读取都重新从页面拉取最新元素 @CacheLookup(false) WebElement labelCalendarMonth; @FindBy(id="txtStartDate_calendarButton") WebElement searchStartDateButton; @FindBy(xpath="//a[@title='Prev']") @CacheLookup(false) WebElement calendarSearchStartDatePreviousBtn; // 最大点击次数设置为12,覆盖全年切换场景,避免目标月份不存在时死循环 private static final int MAX_MONTH_SWITCH = 12; public void selectStartMonth(WebElement ele, String targetMonth) throws InterruptedException { int clickCounter = 0; while (!targetMonth.equals(labelCalendarMonth.getText()) && clickCounter < MAX_MONTH_SWITCH) { ele.click(); // 等待日历切换完成,可根据页面实际响应速度调整休眠时长 Thread.sleep(600); clickCounter++; } // 可选添加断言,避免循环结束后未到达目标月份的情况直接漏测 assert labelCalendarMonth.getText().equals(targetMonth) : "日历未切换到目标月份:" + targetMonth; } public void clickCalendarSearchStartDatePreviousBtn() throws InterruptedException { selectStartMonth(calendarSearchStartDatePreviousBtn, "January"); } @Test() public void testAddResourceSchedule() throws InterruptedException { // 注意要先点击打开日期选择器,再触发月份切换逻辑 searchStartDateButton.click(); resourceSchedulePage.clickCalendarSearchStartDatePreviousBtn(); }
优化建议
可以用Selenium显式等待替代固定的Thread.sleep,根据页面实际变化触发后续逻辑,提升用例稳定性:
// 导入对应依赖后替换Thread.sleep逻辑 WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(2)); // 点击后等待月份元素更新 wait.until(ExpectedConditions.stalenessOf(labelCalendarMonth));
内容的提问来源于stack exchange,提问作者enthusiasticCoder
相关产品推荐
相关产品推荐

