首页 > 解决方案 > 检查在移动屏幕上滑动是否加载了新元素

问题描述

在我们的移动应用程序上,我们有几个屏幕,我们需要在屏幕上滑动以查看元素或滑动加载新元素。在我们的代码中,每当我们去检查一个元素是否存在时,我们都会调用一个方法来检查屏幕上当前的一组元素,然后滑动并在滑动后再次读取屏幕上的所有元素。现在,比较两个列表中的最后一个元素以检查是否加载了新元素。如果没有加载新元素,那么我们得出结论,我们正在寻找的元素没有加载到屏幕上。下面是我为此目的编写的代码。此代码应识别滑动是否正在加载新元素。

问题在于我正在读取所有元素并加载到列表的步骤。这一步变得非常繁重,有时会导致代码执行超过 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;

}

标签: javaseleniumappiumappium-iosappium-android

解决方案


与其匹配滑动前的最后一个元素和滑动后的第一个元素,不如通过检查其列表大小来检查所需元素是否显示在页面上。

假设您的页面上有 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;

推荐阅读