Home > Test Driven Development > Test your web application’s UI with JUnit and Selenium

Test your web application’s UI with JUnit and Selenium


Selenium is a portable Browser automation framework for web applications. Selenium provides a record/playback tool called Selenium Remote Control (RC) 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 it this article I am going to demonstrate you how the 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 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 portion of the screenshot using JUnit and Selenium. The code of this sample web application are listed as below:

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=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">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Enter your name</title>
<h3>Please enter your name</h3>
<form  action="./UserNameServlet" method="post">
		<th><input name="userName" type="text" /></th>
		<td colspan="2" align="right"><input type="submit" value="submit"/></td>

Source Code of index.jsp

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;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	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

<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ page language="java" contentType="text/html; charset=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">
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Welcome Page</title>
<h3 align="center">Welcome ${userName}!!!</h3>

<a href="index.jsp">go back</a>

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 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.
  • 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;
    	public void setUp() {
    		// Create a new instance of the html unit driver
    		driver = new HtmlUnitDriver();
    		//Navigate to desired web page
    	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
    		//verify title of welcome page
    		//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
    		// submit form
    	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

    Source Code of TestEndToEndPages.java

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


This is very basic but workable example that shows you how to use selenium for your web application’s UI automation. For more information you can visit 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

  1. January 13, 2011 at 3:55 pm

    Most what i read online is trash and copy paste but your posts are not alike. Keep it like this.

  2. Bhavana
    May 6, 2011 at 1:10 am

    Hi Bikshaw,

    I’m new to selenium and I’m given to automate UI application using Selenium. Do you have any idea how to verify font colors of links, button etc….or an xpath. In our application when I mouseover the link, it changes to different color which i need to test. Any help on this is much appreciated. Thanks

    • May 6, 2011 at 6:23 pm

      Use Selenium IDE plugin for FireFox to record your action. You can see the source code of the recorded test in various formates like JUnit , Ruby, C# etc (Select Option Menu -> Format to change your source format).
      But changing of color of a link in done through Cascading Style Sheet CSS Hover effects: a:hover {color: #C0FFC0; }. Generally it is mentioned in external CSS file. So, you can locate your link by XPath expression and later can verify its properties. Please refer to the Selenium documentations for more details.

  3. Bhavana
    May 6, 2011 at 1:12 am

    Above article gives really great info. Thanks much for sharing.

  4. Amit
    July 13, 2012 at 9:16 pm

    Looks good, however you are missing an @After annotation for tearing down the constructs once the tests are complete

  5. December 26, 2012 at 11:24 am

    I hope you enjoyed your breakfast. 🙂
    It gives me food for thought that I should start writing again.

  6. Bijay
    March 27, 2017 at 3:28 pm

    Hi Bikash, this is very nice article for new bees . i m c++ Embedded developer.there is newly requirement was come to Test data preparation.

    basically what i mean is that we have jsp page which takes 15 text fields and save in to the data base(basically tester are testing like this:they are entering the data and hiting the save or update button.)

    my requirement is that we need to auto fill these fields and only i will hit the save button.

    How to achieve this .?
    please give some basic information ,either we need to develop plugin with the help of selenium web driver

    Thanks in advance …


    • March 27, 2017 at 9:54 pm

      Hi Bijay,

      I know know how your web-app works. But the idea is populate the fields before clicking submit button. You can’t update the fields value after hitting the submit button as you do not control how the webapp works or alter its behavior.


  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: