首页 > 解决方案 > Selenium - Java - 如何断言/验证页面上的所有链接是否正常工作,获取标题并根据预期标题进行验证

问题描述

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

我有这种方法,它找到页面上某个部分的所有链接,单击每个链接,通过每个选项卡激怒,然后获取每个页面的标题

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

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

我尝试了几种方法来断言通过更改返回类型到 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());
    }

标签: javaseleniumtestingautomated-testspageobjects

解决方案


修改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.

boolean isEmpty = (expectedOnlySet.size() == 0 && actualOnlySet.size() == 0);

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

   // If actualOnlySet contain any title; it means those titles are not expected titles.
   StringBuilder message = new StringBuilder();

   for (String x: expectedOnlySet) {
       message.append("Did not receive: ");
       message.append(x).append(", ");
   }

   for (String y: actualOnlySet) {
       message.append("Not expected but received: ");
       message.append(y).append(", ");
   }

   Assert.assertTrue(false, message,toString());
}else {
   Assert.assertTrue(true);
}

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

我们必须检查这两种情况;

  1. 是否收到所有预期的标题
  2. 预计所有收到的标题

推荐阅读