java - 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());
}
解决方案
修改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() 方法。检查文档
我们必须检查这两种情况;
- 是否收到所有预期的标题
- 预计所有收到的标题
推荐阅读
- html - ReactJs - 以相反的顺序输入数据的奇怪行为
- webrtc - 是否有可能使用 OBS 获得与使用基于 Web 的发布相同的延迟
- netty - Spring Cloud Gateway:RHEL 上的高 CPU 利用率:可以从 epoll 切换到 NIO
- android - 使用 rxjava 中的密封类处理 api 响应
- php - 公开共享团队云端硬盘中的文件
- java - H2db jar 在 8082 以外的端口上不起作用
- python - 如何在浏览器上查看 python 请求在做什么
- python - 带有 Groupby、轴控制的 Pandas 直方图
- deployment - Swagger 工具生产构建节点 js
- flutter - 如何获取资产图像的大小