Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Test your web application’s UI with JUnit and Selenium

5.00/5 (2 votes)
6 Jan 2011CPOL2 min read 78.6K  
Test your web application’s UI with JUnit and Selenium

Background

Selenium is a portable Browser automation framework for web applications. Selenium provides a record/playback tool called Selenium Remote Control (RC) that runs your tests in multiple browsers and platforms for authoring tests without learning a test scripting language. Selenium also provides Firefox add-on that records clicks, typing, and other actions to make a test, which you can play back in the browser, known as Selenium IDE.
But in this article, I am going to demonstrate how to use Selenium Java WebDriver API to automate your web application or any third party web application.

Create a Simple Web Application

First of all, you need to have a web application in place which you want to test. Let’s assume you have an existing application like I am going to show you now. In this application, the users have to enter their name to go to the welcome page and then they can go back to the input page. Refer to the screenshots of the application:

index page screenshot

Index Page Screenshot

welcome page screenshot

Welcome Page Screenshot

In the following sections, you will find how to test all highlighted portions of the screenshot using JUnit and Selenium. The code of this sample web application is listed as below:

XML
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Enter your name</title>
</head>
<body>
<h3>Please enter your name</h3>
<form  action="./UserNameServlet" method="post">
<table>
	<tr>
		<th>Name:</th>
		<th><input name="userName" type="text" /></th>
	</tr>
	<tr>
		<td colspan="2" align="right"><input type="submit" value="submit"/>
		</td>
	</tr>
</table>
</form>
</body>
</html>
Source Code of index.jsp
Java
package blog.selenium;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author Bikash Shaw
 */
public class UserNameServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest request, 
		HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	@Override
	protected void doPost(HttpServletRequest request, 
		HttpServletResponse response) throws ServletException, IOException {
		processRequest(request,response);
	}

	private void processRequest(HttpServletRequest request, 
		HttpServletResponse response) throws IOException, ServletException{
		String userName = request.getParameter("userName");
		HttpSession session = request.getSession();
		session.setAttribute("userName", userName);
		request.getRequestDispatcher("welcome.jsp").forward(request, response);
	}
}
Source Code of UserNameServlet.java
Java
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Welcome Page</title>
</head>
<body>
<h3 align="center">Welcome ${userName}!!!</h3>

<a href="index.jsp">go back</a>
</body>
</html>
Source Code of welcome.jsp

Before you are going to write test cases, make sure the application you want to test is up and running.

Test Web Application Using JUnit and Selenium

Before I illustrate the code of how to test the UI, let’s understand the core Selenium classes which are used most frequently to write test cases.

  • org.openqa.selenium.WebDriver: The main interface to use for testing, which represents an idealised web browser. The methods in this class fall into three categories – Control of the browser itself, Selection of WebElements, Debugging aids
  • org.openqa.selenium.WebElement: Represents an HTML element. Generally, all interesting operations to do with interacting with a page will be performed through this interface.
  • org.openqa.selenium.By: Mechanism used to locate elements within a document.
    Java
    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://localhost:6060/WebApplication4Selenium");
    	}
    
    	@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("Allen");
    
    		//verify title of welcome page
    		verifyTitle("Welcome");
    
    		//verify header of welcome page
    		verifyHeaderMessage("Welcome Allen!!!");
    
    		//verify back link and click on it
    		backToPreviousPage("go 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();
    	}
    }
    Source Code of TestEndToEndPages.java

If you look closely at the comments in the above mentioned test class, you will be able to find how you can navigate to a page or how you can find an element to perform certain operations like get the text, set a value, trigger any event, etc.

Resources

This is very basic but a workable example that shows you how to use selenium for your web application’s UI automation. For more information, you can visit the official selenium sites listed below:

  1. Download Selenium IDE, RC etc.: http://seleniumhq.org
  2. Google code base for Selenium: http://code.google.com/p/selenium/
  3. Documentation of Selenium JAVA API: http://wiki.openqa.org/display/SEL/Home


License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)