-1

我有一种搜索方法,在第一页上有一个维基百科的链接:

public void findWiki() {

    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']"));

    if (TryLink.isDisplayed()) {
        System.out.println("Yes link is there");
    } else {
        System.out.println("No link is there");
    }
}

该方法的实现:

@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");
    googleSearchPF.findWiki();
}

测试有效,一切正常 - 它找到了链接。但是如何使用 assertTrue 实现链接检查?如果是这样,具体如何?

似乎它应该以某种方式实现,如下所示:

Assertions.assertTrue(googleSearchPF.getAllElements().stream().anyMatch(x->x.isDisplayed()),
        "Wikipedia was not found");
4

2 回答 2

1

要使您findWiki()的断言可以如下完成:

public void findWiki() {

    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']"));

    assertTrue(TryLink.isDisplayed(),"No link is there"));
}
于 2021-09-12T16:21:47.783 回答
1

如果你看到assertTrue

assertTrue
public static void assertTrue(java.lang.String message,
                              boolean condition)
Asserts that a condition is true. If it isn't it throws an AssertionError with the given message.
Parameters:
message - the identifying message for the AssertionError (null okay)
condition - condition to be checked

现在,您的findWiki()方法确实包含 if 和 else 块,我相信您想要断言并摆脱传统if else的检查conditions.

代码 :

public void findWiki() {
    List<WebElement> TryLink = driver.findElements(By.xpath("//a[@href='https://ru.wikipedia.org/wiki/%D0%A8%D0%BF%D0%B0%D0%B6%D0%BD%D0%B8%D0%BA']"));
    int size = TryLink.size() ;
    assertTrue(size > 0, "try link exists"); 
}

基本上我们正在使用findElements并检查大小,如果它>0在里面解析,assertTrue.就像这样assertTrue(size > 0, "try link exists");

于 2021-09-12T16:22:47.633 回答