JUnit HttpUnit Example

Hello, in this example we shall show you how you can make a use of the JUnit HTTUnit to test web applications. In this example, we will build a small web application and test it using HTTPUnit. This example will show you how you can achieve a browser specific behaviour with HTTPUnit library like sending requests to the server and receiving response from the server.

1. Introduction

HttpUnit is an open source test framework for web applications which can provide browser specific behaviour like sending request to the server and receiving response from the server including form submission, basic http authentication, cookies and automatic page redirection.

A website has several forms with multiple textboxes, dropdowns, radio buttons, submit buttons, links etc. In order to test a form submission, you test whether dropdowns are populated with the desired values, all the controls are set with their default values ,if any, and submit buttons redirect the user to their desired page. Testing a form is one of the many test cases for a website that can be tested using Httpunit.

2. JUnit HttpUnit Example

Here is a step-by-step guide to test your web application using HTTPUnit.

2.1 Tools Used

We are using Spring sts 3.9, JDK 8, HttpUnit 1.7.

2.2 Project Structure

The following image of the final project structure shows where I should create the required files and folders .

Fig.1: Project Structure

2.3 Project Creation

This section will demonstrate on how to create a Java-based Maven project in Spring sts. In spring sts go to File-->New-->Maven Project.

Fig.2: Create Maven Project

In the new Maven Project window, it will ask you to select a project location. By default ‘Use default workspace location‘ is selected. Just click on next button to proceed.

Fig.3: Project details

Select the archetype for web app.

Fig.4: ArcheType Selection

Enter the group details and the artifact id for the project as shown. The version number will be by default: 0.0.1-SNAPSHOT.

Fig.5: ArcheType Parameters

Click on finish and a maven project will be created with an initial draft of pom.xml with the following details:


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

We can now start adding dependency to this pom.xml for our web application and httpunit. We will be building this web application using spring boot, so lets start!!!

3. Application Building

Below are the steps involved in developing this application.

3.1 Maven Dependencies


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
            <!-- JSTL tag lib -->

             <!-- Tomcat for JSP rendering -->
             <!-- dependency for js.jar -->

Httpunit jar and js.jar are the two dependencies required to test this web application using HTTPUnit. We are building this web application using spring boot, hence we have added all the spring boot related dependencies along with Tomcat dependency to enable the embedded Tomcat container.

3.2 Java Class Creation

Let’s create the required Java files. Right-click on src/main/java folder, New -> Package.

Fig.6: Java Package Creation

A new pop window will open where we will enter the package name as: com.httpunitsample.controller.

Fig.7: Java Package creation for controller

Following the above two steps for package creation, create two more packages for form and a main application class i.e com.httpunitsample.form and com.httpunitsample.main.

Once the package is created, we now need to create the implementation classes. Right-click on the newly created package, New -> Class.

Fig.8: Java class creation

A new pop window will open, enter file name as: RegistrationController. A new controller class will be created inside the package: com.httpunitsample.controller.

Fig.9: Java controller creation

Following the above steps for class creation, create a class for RegistrationForm.java and Main.java under the package com.httpunitsample.form and com.httpunitsample.main respectively.

Now, lets create a views folder under WEB-INF for jsps as shown below.

Fig.10: View folder for jsp

Create a Registration.jsp under the views folder.

Fig.11: Jsp file creation

Following the above steps create another Hello.jsp under the WEB-INF/views folder.

Lets create a application.properties file under src/main/resources for jsp views to be resolved .

Fig.12: Application property file

Below is the code for the classes defined above.


package com.httpunitsample.controller;

import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.httpunitsample.form.RegistrationForm;

public class RegistrationController {

	@RequestMapping(value = "/registrationForm")
    public String registration(Model model) {
		RegistrationForm registrationForm=new RegistrationForm();
		List countryList=new ArrayList();
        List genderList=new ArrayList();
        genderList.add("Dont want to say");
        model.addAttribute("genderList", genderList);
        //Set default value in gender list dropdown.
        registrationForm.setGender("Dont want to say");
        model.addAttribute("registrationForm", registrationForm);
        return "Registration";
	@RequestMapping(value = "/registrationSubmit")
    public String registerUser(RegistrationForm registrationForm,Model model) {
        return "Hello";

In the above controller class, I have defined two methods:

  1. registration – This method returns a registration form set with default values.
  2. registerUser – This method returns a hello page to the user, populated with the registered username.


package com.httpunitsample.form;

public class RegistrationForm {

	private int id;
	private String name;
	private String gender;
	private String countryId;

	public int getId() {
		return id;

	public void setId(int id) {
		this.id = id;

	public String getName() {
		return name;

	public void setName(String name) {
		this.name = name;

	public String getGender() {
		return gender;

	public void setGender(String gender) {
		this.gender = gender;

	public String getCountryId() {
		return countryId;

	public void setCountryId(String countryId) {
		this.countryId = countryId;


Above is the defined form that will be used for user registration.


package com.httpunitsample.main;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

public class Main {

	public static void main(String[] args) {
	      SpringApplication.run(Main.class, args);

Main.java is the main class that will be called on running the spring boot application.


<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<h2>Thank you for registration ${name}</h2>

Hello.jsp page is shown on successful registration with registered username.


<%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html lang="en">
    <title>Create an account</title>
<h1>Welcome to httpunit example registration</h1>
<div class="container">
    <form:form method="POST" commandName="registrationForm" action="registrationSubmit">
        <spring:bind path="name">
                <form:input type="text" path="name"></form:input>

        <spring:bind path="gender">
                <form:select path="gender" >
                 <c:forEach items="${genderList}" var="gender">
					<c:when test="${registrationForm.gender eq gender}">
					<option value="${gender}" selected ="selected"><c:out value="${gender}"/></option>
					<option value="${gender}"><c:out value="${gender}" /></option>

       <spring:bind path="countryId">
                <form:select path="countryId" items="${countryList}" />

        <button type="submit">Submit</button>


Registration.jsp page is shown to the user for registration with default values gender list.


spring.mvc.view.prefix = /WEB-INF/views/
spring.mvc.view.suffix = .jsp

Let us write a test class to test our controller under the package com.httpunitsample.controllertest.

We achieved browser specific behaviour through class WebConversation.java in Httpunit jar. We sent various requests under test and we received corresponding response for such requests. We then examined these response further.

In my below test controller, I have written two test methods to test the following functionalities:

  1. The registration method in controller returns a registration form with default value for gender list and country dropdown lists with all the required values.
  2. RegisterUser method in controller, sets the registered name and redirects to hello jsp page. Using httpunit, I test if user is redirected to the desired hello page or not.


package com.httpunitsample.controllertest;

import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertThat;
import java.io.IOException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.junit4.SpringRunner;
import org.xml.sax.SAXException;
import com.meterware.httpunit.WebConversation;
import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebResponse;

public class RegistrationControllerTest {

		public void registrationTest() throws IOException, SAXException {
			 WebConversation wc = new WebConversation();
			 WebResponse   resp = wc.getResponse( "http://localhost:8080/registrationForm" );
			 WebForm form = resp.getForms()[0];
			 assertEquals( "", form.getParameterValue( "name" ) );
			 assertEquals( "Dont want to say",       form.getParameterValue( "gender" ) );
			 assertEquals( "America",      form.getParameterValue( "countryId" ) );
		public void registerUserTest() throws IOException, SAXException {
			 WebConversation wc = new WebConversation();
			 WebResponse   resp = wc.getResponse( "http://localhost:8080/registrationForm" );
			 WebForm form = resp.getForms()[0];
			 form.setParameter("name", "Gaurav" );
			 form.setParameter("gender", "Male");
			 form.setParameter("countryId", "India");
			 WebResponse response=form.submit();
			 assertThat(response.getText(),containsString("Thank you for registration "));

3.3 Maven Build

I can build my application with command as Run As-->Maven Build--> Provide goals as clean package. In case I want to build without running the test cases I can build using the command Run As-->Maven Build-->Provide goals as clean package -Dmaven.test.skip=true.

Fig.13: Maven Build

4. Run application as spring boot app

Run the application as below:

Fig.14: Spring boot App

5. Project Demo

Running the code on the browser gives us the following results:

Fig.15: Screen1

Fig.16: Second screen

Fig.17: Junit test run

As per the above screenshot my junit tests are successful.

Here I have tested two test cases:

  1. Form is populated with the set default value i.e "gender". The dropdown has "Dont want to say" value, the name text box is blank and countryId dropdown is populated with America and India.
  2. In the second test method I have tested the submit functionality of my form whether I am forwarded to my desired Hello page or not.

6. Conclusion

That’s all for getting the developers started with the Httpunit. I hope this article served you well. Developers can download the sample application as an Eclipse project in the Downloads section.

7. Download the project

This was an example on how you can use HttpUnit to test your website.

You can download the full source code of this example here: JUnit HttpUnit Example

Garima Pandey

Garima is a software developer and have more than 7 years of experience in web application development using various java technologies with a passion to write quality code.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button