You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JUnit中使用Assert替代if-else完成Selenium链接存在性校验

实现方案

方案1:最小改动现有代码

先修改原findWiki方法,将打印逻辑改为返回布尔值,同时捕获元素不存在的异常避免测试直接中断:

public boolean isWikiLinkDisplayed() {
    try {
        WebElement TryLink = chromeDriver.findElement(By.xpath("//a[@href='https://ru.wikipedia.org/wiki/%D0%A8%D0%BF%D0%B0%D0%B6%D0%BD%D0%B8%D0%BA']"));
        return TryLink.isDisplayed();
    } catch (NoSuchElementException e) {
        // 元素不存在时直接返回false
        return false;
    }
}

之后在测试方法中直接调用断言即可:

@Test
public void googleSearchPF() {
    chromeDriver.get("https://www.google.com/webhp?hl=en&sa=X&ved=0ahUKEwi88p6D9vbyAhXhkIsKHffmA_oQPAgI");
    GoogleSearchPF googleSearchPF = PageFactory.initElements(chromeDriver, GoogleSearchPF.class);
    googleSearchPF.find("Gladiolus");
    Assertions.assertTrue(googleSearchPF.isWikiLinkDisplayed(), "Wikipedia was not found");
}

方案2:按你预期的流式匹配实现

如果希望批量匹配所有搜索结果中的维基链接、不用写死完整href,可以先在Page类中新增获取所有搜索结果链接的方法:

public List<WebElement> getAllSearchResultLinks() {
    // 可调整XPath只匹配搜索结果区域的a标签,避免匹配到页脚等无关位置的链接
    return chromeDriver.findElements(By.xpath("//div[@id='search']//a"));
}

之后在测试中直接用流式逻辑校验即可:

@Test
public void googleSearchPF() {
    chromeDriver.get("https://www.google.com/webhp?hl=en&sa=X&ved=0ahUKEwi88p6D9vbyAhXhkIsKHffmA_oQPAgI");
    GoogleSearchPF googleSearchPF = PageFactory.initElements(chromeDriver, GoogleSearchPF.class);
    googleSearchPF.find("Gladiolus");
    
    Assertions.assertTrue(
        googleSearchPF.getAllSearchResultLinks().stream()
            .filter(WebElement::isDisplayed)
            .anyMatch(link -> link.getAttribute("href").contains("wikipedia.org")),
        "Wikipedia was not found in search results"
    );
}

补充优化提示

  • 如果使用Selenium PageFactory注解,可以直接将维基链接的定位写在字段上,简化代码:
@FindBy(xpath = "//a[contains(@href,'wikipedia.org')]")
private List<WebElement> wikiLinks;

public boolean hasDisplayedWikiLink() {
    return wikiLinks.stream().anyMatch(WebElement::isDisplayed);
}
  • 代码用到的NoSuchElementException来自org.openqa.selenium.NoSuchElementException,JUnit5的Assertions来自org.junit.jupiter.api.Assertions,注意提前导入对应依赖。

内容的提问来源于stack exchange,提问作者Otto Rahn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:15:00