Selenium-Java-如何断言/验证页面上的所有链接是否正常工作,获取标题并针对预期标题进行验证

问题描述 投票:0回答:1

我是自动化测试的新手,目前正在从事个人项目

我有这种方法,它可以找到页面上某个部分的所有链接,单击每个链接,对每个选项卡进行刺激,然后获取每个页面的标题

但是,我想要一种方法来根据预期标题列表来验证这些链接的标题

为了做到这一点,修改它的最佳方法是什么?最好将其存储在数组中,然后分别声明/验证每个标题?

我尝试了几种方法来通过更改将断言返回类型声明为String以及List,但是没有运气

public void linksAreWorkingDashBoardLeftPanal() throws Exception {

    List<WebElement> li_All = links_myAccountNav.findElements(By.tagName("a"));
    for(int i = 0; i < li_All.size(); i++){

        String clickOnLinkTab = Keys.chord(Keys.CONTROL, Keys.ENTER);
        links_myAccountNav.findElements(By.tagName("a")).get(i).sendKeys(clickOnLinkTab);
        Thread.sleep(5000);

    }//Opens all the tabs 
        Set<String> getTitleinWindow = driver.getWindowHandles(); 
        Iterator<String> it = getTitleinWindow.iterator();

        while(it.hasNext()){

          driver.switchTo().window(it.next());
          System.out.println(driver.getTitle());
java selenium testing automated-tests pageobjects
1个回答
0
投票

如下修改while循环;

List<String> expectedTitleList = new ArrayList<>(); 
// Get the expected titles in a list. 
// You have to initiate and add expected titles to this list, before running the while loop.

List<String> actualTitleList = new ArrayList<>();
    while(it.hasNext())
    {
          driver.switchTo().window(it.next());
          actualTitleList.add(driver.getTitle());
    }

// Create copies of each list;
Set<String> expectedSet = new HashSet<>(expectedTitleList);
Set<String> actualSet = new HashSet<>(actualTitleList);

Set<String> expectedOnlySet = new HashSet<>(expectedSet);
Set<String> actualOnlySet = new HashSet<>(actualSet);

expectedOnlySet.removeAll(actualSet);
actualOnlySet.removeAll(expectedSet);

// Check if expectedOnlySet and actualOnlySet are empty
// If both of them are empty then all titles are received as expected.

if (expectedOnlySet.size() > 0) {
   // If expectedOnlySet contain any title; it means those titles are not opened in the browser. 

   //(Reasons can be; either the links are broken or existing title name changed.)
}

if (actualOnlySet.size() > 0) {
   // If actualOnlySet contain any title; it means those titles are not expected titles. 

   // (Reasons can be; either new link added with new title or changed titles.)
}

这里您可以在Collections中使用removeAll()方法。检查documentation

我们必须检查两种情况;是否已收到所有预期的标题,以及是否预期所有已接收的标题。

© www.soinside.com 2019 - 2024. All rights reserved.