Using Jetty Server with Junit test

In this post I will show you how to use Jetty server with Junit test case and how to deploy web application using Java program in Junit test.

If you already have an idea on how to create a maven project in Eclipse will be great otherwise I will tell you here how to create a maven project in Eclipse.
Prerequisites
The following configurations are required in order to run the application
Eclipse Kepler
JDK 1.7
Tomcat 7
Have maven installed and configured
Jetty and Junit dependencies in pom.xml
Now we will see the below steps how to create a maven based spring project in Eclipse
First we will create service project
Step 1. Create a maven based web project in Eclipse

Go to File -> New -> Other. On popup window under Maven select Maven Project. Then click on Next. Select the workspace location – either default or browse the location. Click on Next. Now in next window select the row as highlighted from the below list of archtypes and click on Next button.

maven-arctype-webapp
Now enter the required fields (Group Id, Artifact Id) as shown below
Group Id : com.roytuts
Artifact Id : webapp
Step 2. Modify the pom.xml file as shown below.

<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">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.roytuts</groupId>
    <artifactId>webapp</artifactId>
    <packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version>
    <name>webapp Maven Webapp</name>
    <url>http://maven.apache.org</url>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <jdk.version>1.7</jdk.version>
        <junit.version>4.11</junit.version>
        <jetty.version>6.1.26</jetty.version>
        <jsp.version>2.1.v20100127</jsp.version>
    </properties>
    <dependencies>
        <!-- JETTY -->
        <dependency>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jetty</artifactId>
            <version>${jetty.version}</version>
        </dependency>
        <dependency>
            <groupId>org.mortbay.jetty</groupId>
            <artifactId>jsp-2.1-glassfish</artifactId>
            <version>${jsp.version}</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
    </dependencies>
    <build>
        <finalName>webapp</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <configuration>
                    <source>${jdk.version}</source>
                    <target>${jdk.version}</target>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Step 3. If you see JRE System Library[J2SE-1.4] then change the version by below process

Do right-click on the project and go to Build -> Configure build path, under Libraries tab click on JRE System Library[J2SE-1.4], click on Edit button and select the appropriate jdk 1.7 from the next window. Click on Finish then Ok.

Step 4. Modify web.xml file as below

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
    version="3.0">
    <display-name>Webapp</display-name>
</web-app>

Step 5. Create Junit test class for testing with Jetty server

package com.roytuts.webapp.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
public class WebappTest {
  private Server server;
  @Before
  public void setUp() throws Exception {
    server = new Server(8080);
    server.setStopAtShutdown(true);
    WebAppContext webAppContext = new WebAppContext();
    webAppContext.setContextPath("/webapp");
    webAppContext.setResourceBase("src/main/webapp");
    webAppContext.setClassLoader(getClass().getClassLoader());
    server.addHandler(webAppContext);
    server.start();
  }
  @After
  public void tearDown() throws Exception {
    server.stop();
  }
  @Test
  public void testWebappDeploy() {
    HttpURLConnection connection = null;
    try {
      URL url = new URL("http://localhost:8080/webapp/");
      connection = (HttpURLConnection) url.openConnection();
      if (connection.getResponseCode() != 200) {
        throw new RuntimeException("Failed! HTTP Error Code: " + connection.getResponseCode());
      }
      BufferedReader br = new BufferedReader(new InputStreamReader((connection.getInputStream())));
      String str;
      while ((str = br.readLine()) != null) {
        System.out.println(str);
      }
    } catch (MalformedURLException e) {
      e.printStackTrace();
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
      if (connection != null) {
        connection.disconnect();
      }
    }
  }
}

Step 6. Run the above Junit test class, you will see the below output in the console

2016-01-19 11:30:24.886:INFO::Logging to STDERR via org.mortbay.log.StdErrLog
2016-01-19 11:30:24.933:INFO::jetty-6.1.26
2016-01-19 11:30:25.370:INFO::Started SocketConnector@0.0.0.0:8080
2016-01-19 11:30:26.681:INFO::Stopped SocketConnector@0.0.0.0:8080
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>
2016-01-19 11:30:26.806:INFO::Shutdown hook executing
2016-01-19 11:30:26.806:INFO::Shutdown hook complete

Thanks for reading.

Leave a Reply

Your email address will not be published. Required fields are marked *