Issue
I have a method for searching that on the first page there is a link to wikipedia:
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");
}
}
Implementation of this method:
@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();
}
The test works, everything is OK - it finds the link. But how can I implement a link check using assertTrue? If so, how exactly?
It seems that it should be implemented somehow like this:
Assertions.assertTrue(googleSearchPF.getAllElements().stream().anyMatch(x->x.isDisplayed()),
"Wikipedia was not found");
Solution
If you see 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
Now, Your findWiki()
method does contains if and else block, which I believe you want to assert and get rid off of that traditional if else
to check the conditions
.
Code :
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");
}
Basically we are using findElements
and checking the size if it's >0
then parse inside assertTrue.
Like this assertTrue(size > 0, "try link exists");
Answered By - cruisepandey
Answer Checked By - Dawn Plyler (JavaFixing Volunteer)