Which assert should I use? Will you please provide an example?
The code currently opens the selenium website and clicks on the "downloads" link.
On the downloads page there is a h2 heading named Downloads.
<h2>Downloads</h2>
How can I verify that there is a heading with the text Downloads and that is surrounded by h2 tags?
If I can't add an assert line into the "test" method, will you please help me with figuring out how to create and call the required method within in below code. I am new to java and selenium. Thank you for any help you can provide.
import java.util.regex.Pattern;
import java.util.concurrent.TimeUnit;
import org.junit.*;
import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;
import org.openqa.selenium.*;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.Select;
public class guayaki {
private WebDriver driver;
private String baseUrl;
private boolean acceptNextAlert = true;
private StringBuffer verificationErrors = new StringBuffer();
@Before
public void setUp() throws Exception {
driver = new FirefoxDriver();
baseUrl = "http://www.seleniumhq.org/";
driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
}
@Test
public void testGuayaki() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.linkText("Download")).click();
}
@After
public void tearDown() throws Exception {
//driver.quit();
String verificationErrorString = verificationErrors.toString();
if (!"".equals(verificationErrorString)) {
fail(verificationErrorString);
}
}
private boolean isElementPresent(By by) {
try {
driver.findElement(by);
return true;
} catch (NoSuchElementException e) {
return false;
}
}
private boolean isAlertPresent() {
try {
driver.switchTo().alert();
return true;
} catch (NoAlertPresentException e) {
return false;
}
}
private String closeAlertAndGetItsText() {
try {
Alert alert = driver.switchTo().alert();
String alertText = alert.getText();
if (acceptNextAlert) {
alert.accept();
} else {
alert.dismiss();
}
return alertText;
} finally {
acceptNextAlert = true;
}
}
}
You can use xpath and findElements
for this:
@Test
public void testGuayaki() throws Exception {
driver.get(baseUrl + "/");
driver.findElement(By.linkText("Download")).click();
List<WebElement> downloadHeader = driver.findElements(By.xpath("//h2[contains(text(), 'Downloads')]"));
if(downloadHeader.size() > 0)
{
System.out.println("Found h2 header Downloads");
}
}
If you want to perform an exact match, you can modify the xpath as follows:
//h2[text() = 'Downloads']