java - 检查在移动屏幕上滑动是否加载了新元素
问题描述
在我们的移动应用程序上,我们有几个屏幕,我们需要在屏幕上滑动以查看元素或滑动加载新元素。在我们的代码中,每当我们去检查一个元素是否存在时,我们都会调用一个方法来检查屏幕上当前的一组元素,然后滑动并在滑动后再次读取屏幕上的所有元素。现在,比较两个列表中的最后一个元素以检查是否加载了新元素。如果没有加载新元素,那么我们得出结论,我们正在寻找的元素没有加载到屏幕上。下面是我为此目的编写的代码。此代码应识别滑动是否正在加载新元素。
问题在于我正在读取所有元素并加载到列表的步骤。这一步变得非常繁重,有时会导致代码执行超过 5 分钟。
有人可以建议我是否可以在这里做得更好。
public synchronized boolean isScrollingLoadsNewElement (AppiumDriver<MobileElement> driver)
{
boolean isNewElementLoaded = false;
System.out.println("inside the new method to scroll and check new element");
//declare a list to accept all the elements on current screen
//go to the end of the list to read the last element. Store in a variable
this.driver = driver;
List<MobileElement> lAllElements = this.driver.findElements(By.xpath(".//*"));
System.out.println("list of element before swiping has been read");
MobileElement lastElement = lAllElements.get(lAllElements.size()-1);
//scroll and then again read the list of all elements.
//read the last element on the list and then compare the elements on above 2 steps.
//if the elements are different than return true else false.
swipeScreen(driver);
List<MobileElement> lAllElementsAfterSwipe = this.driver.findElements(By.xpath(".//*"));
System.out.println("list of element after swiping has been read");
MobileElement lastElementAfterSwipe = lAllElementsAfterSwipe.get(lAllElementsAfterSwipe.size()-1);
if (lastElementAfterSwipe.equals(lastElement))
isNewElementLoaded = false;
else
isNewElementLoaded = true;
return isNewElementLoaded;
}
解决方案
与其匹配滑动前的最后一个元素和滑动后的第一个元素,不如通过检查其列表大小来检查所需元素是否显示在页面上。
假设您的页面上有 4 个元素,加载后,显示第 5 个元素,按照您的方法,您将检查第 5 个元素与第 4 个元素不同,并且您将通过测试用例,但这不会让您确定显示的元素是您正在寻找的元素,因为第 5 个元素可以是任何其他不打算显示在页面上但按照您的逻辑的元素,测试用例将通过。
因此,您应该获取要查找的元素的 xpath,然后在每次滑动后检查元素列表大小,因为元素列表大小在页面上显示时将大于 0,您应该限制滑动到一个限制,以便在该次数的滑动之后,您应该将布尔值返回为 false,否则循环将在无限状态下继续以检查元素是否存在。
你的代码逻辑应该是这样的:
List<WebElement> element = driver.findElements(By.xpath("mention the xpath of the element that needs to be found"));
boolean elementLoaded = false;
int swipeCount = 0;
// Taking the swipeCount limit as 5 here
while (!elementLoaded && swipeCount < 5) {
if (element.size() == 0) {
// Swipe the screen
swipe(driver);
swipeCount++;
} else {
elementLoaded = true;
}
}
return elementLoaded;
推荐阅读
- gitlab - 如何为 Gitlab 指定 pre-commit --from-ref?
- android - react-native run-android:此版本中使用了已弃用的 Gradle 功能,使其与 Gradle 7.0 不兼容
- security - Wildfly 24,部署不使用wildfly安全的应用
- javascript - 我想动态使用 ngb 字体,但是当我点击任何一个时,它会打开所有的字体
- asynchronous - 什么是异步,响应式编程必须是异步的吗?
- android - 我无法在 gradle 7.0.0 和 android studio 2020.3.1 中添加 MPAndroidChart
- android - 如何解决“Attribute android: ** not allowed here”错误?
- reactjs - 将认知用户名显示为文本
- python-3.x - 正则表达式第一次出现字符串搜索给出 NULL 输出
- unix - awk 获取一年中所有月份的最后一个工作日