Selenium WebDriver- Web Application Testing : Selenium Example
Selenium Example |
Test Code of Selenium Web Driver
package com.javaskool;
import static org.hamcrest.Matchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Before;
import org.junit.Test;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
public class TestEndToEndPages {
private WebDriver driver;
@Before
public void setUp() {
// Create a new instance of the html unit driver
driver = new HtmlUnitDriver();
//Navigate to desired web page
driver.get("http://127.0.0.1:8081/myseleniumtest.com");
}
@Test
public void shouldBeAbleEnterUserNameAndClickSubmitToVerifyWelcomeMessage()
{
// verify title of index page
verifyTitle("Enter your name");
//verify header of index page
verifyHeaderMessage("Please enter your name");
//enter user name as Allen
enterUserName("James");
//verify title of welcome page
verifyTitle("Welcome");
//verify header of welcome page
verifyHeaderMessage("1Welcome James!!!");
//verify back link and click on it
//backToPreviousPage("back");
//verify title of index page again to make sure link is working
//verifyTitle("Enter your name");
}
private void verifyTitle(String expectedTitle) {
//get the title of the page
String actualTitle = driver.getTitle();
// verify title
assertThat(actualTitle, equalTo(expectedTitle));
}
private void verifyHeaderMessage(String expectedHeaderMessage) {
// find header element
WebElement element = driver.findElement(By.tagName("h3"));
String actualHeaderMessage = element.getText();
// verify header text
assertThat(actualHeaderMessage, equalTo(expectedHeaderMessage));
}
private void enterUserName(String userName) {
// find the input text box
WebElement element = driver.findElement(By.name("userName"));
// set the user name in input text box
element.sendKeys(userName);
// submit form
element.submit();
}
private void backToPreviousPage(String expectedLinkText) {
// find the link by its id
WebElement element = driver.findElement(By.id("back"));
//get the actual link text
String actualLinkText = element.getText();
//verify link text with expected like text
assertThat(actualLinkText, equalTo(expectedLinkText));
// click the link
element.click();
}
}
Create web Project and ADD selenium-java-2.44.0.zip file after extract by using configure build path to Your project as below.
Note: You can take web sample code that is available on previous article.
If you have downloaded above zip file and configured with eclipse then you are ready to move with Selenium Testing Framework.
Run the TestFile which is mentioned as below
And you will find that all tests got successful. since we have the code
verifyHeaderMessage("Welcome James!!!");
Now, Change code as below
verifyHeaderMessage("1Welcome James!!!");
and then run the test again where you will find that test got failed.
Downloads Example |
Recent Comments