Friday 17 April 2015

Struts2 Junit integration


Struts2 provides junit plugin library, to test action classes. This tutorial will provide you an example, how to use junit plugin in struts2.

Step 1:  Create new dynamic web project.

Give the project name as “struts_junit_tutorial” and press next.


Press next and tick the check box “Generate web.xml deployment descriptor” and press finish.

 
Project structure looks like below.


Step 2: Convert project to maven project.
Right click on the project -> go to configure -> Convert to Maven Project


Give Group Id, Artifact Id as “struts_junit_tutorial” and press finish.

 
Now, project structure looks like below.

Step 3: Open pom.xml and update maven dependencies for struts2 and junit plugin for struts2.
pom.xml
<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/xsd/maven-4.0.0.xsd">
 <modelVersion>4.0.0</modelVersion>
 <groupId>struts_junit_tutorial</groupId>
 <artifactId>struts_junit_tutorial</artifactId>
 <version>0.0.1-SNAPSHOT</version>
 <packaging>war</packaging>
 <properties>
  <struts_version>2.3.20</struts_version>
 </properties>
 <build>
  <sourceDirectory>src</sourceDirectory>
  <plugins>
   <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
     <source>1.6</source>
     <target>1.6</target>
    </configuration>
   </plugin>
   <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <version>2.4</version>
    <configuration>
     <warSourceDirectory>WebContent</warSourceDirectory>
     <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
   </plugin>
  </plugins>
 </build>
 <dependencies>
  <dependency>
   <groupId>org.apache.struts</groupId>
   <artifactId>struts2-core</artifactId>
   <version>${struts_version}</version>
  </dependency>
  <dependency>
   <groupId>org.apache.struts</groupId>
   <artifactId>struts2-junit-plugin</artifactId>
   <version>${struts_version}</version>
  </dependency>

 </dependencies>

</project>


Step 3: In struts2 environment, we have to handover the requests to struts2. We do this by configuring web.xml.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>struts_junit_tutorial</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <display-name>Struts2 Demo App</display-name>
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class> org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

As you observe web.xml, we are forwarding all the requests to struts2 environment by using filter mapping. So now it is struts2 responsibility to process this request.

Step 4: in struts2 environment, action class handles request, so we create one action class, called NumberAction.java, in the package junit.struts.
package junit.struts;

public class NumberAction {
 private int num;

 public int getNthPrime(){
  int candidate, count;
     for(candidate = 2, count = 0; count < num; ++candidate) {
         if (isPrime(candidate)) {
             ++count;
         }
     }
     return candidate-1;
 }
 
 public static boolean isPrime(int n) {
     for(int i = 2; i < n; ++i) {
         if (n % i == 0) {
             return false;
         }
     }
     return true;
 }
 
 public String execute(){
  if(getNthPrime() > 1000){
   return "success";
  }
  else{
   return "failure";
  }
 }

 public int getNum() {
  return num;
 }

 public void setNum(int num) {
  this.num = num;
 }
 
}

NumberAction class contains 3 methods.
getNthPrime : Returns the nth prime number
isPrime : Returns true if the number is prime, else false
execute : return succss if the nth prime > 1000, else false.

Step 5: Before writing and executing junit test cases for this action class, I want to show complete application here.
Create index.html, with following code
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
 <form action="numCheck">
  <input type="text" name="num" />
  <input type="submit" value="submit" />
 </form>
</body>
</html>

Create success.jsp with following code.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hurray, your prime number greater than 1000</h1>
</body>
</html>

Create failure.jsp with following code.
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hmmmmm, your prime number is less than 1000</h1>
</body>
</html>


Step 6: It is time to create struts.xml. Since Struts 2 requires struts.xml to be present in classes folder. So create struts.xml file under the WebContent/WEB-INF/classes folder. Eclipse does not create the "classes" folder by default, so you need to do this yourself. To do this, right click on the WEB-INF folder in the project explorer and select New > Folder.

Create struts.xml file inside classes.

struts.xml
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
    <package name="default" extends="struts-default">
        <action name="numCheck" class="junit.struts.NumberAction">
            <result name="success">/success.jsp</result>
            <result name="failure">/failure.jsp</result>
        </action>
    </package>
</struts>


Step 7: Run the Application. Before running make sure, your project structure like below.
Once you ran the application, you can able to see application in the browser like below.


Enter some number and press submit, you will get success.jsp (or) failure.jsp depends on your input.

I entered 400 as input and press submit, I got following screen as output.


Testing action class using junit
It is time to work with junit to test Action class NumberAction.java
Create a package junit.tests and create a class “TestNumberAction” inside the package “junit.tests”.

package junit.tests;

import junit.struts.NumberAction;

import org.apache.struts2.StrutsTestCase;

import com.opensymphony.xwork2.ActionProxy;

public class TestNumberAction extends StrutsTestCase{
 public void testGetNthPrime() throws Exception{
        request.setParameter("num", "1");
        
        ActionProxy proxy = getActionProxy("/numCheck");
        NumberAction numberAction = (NumberAction) proxy.getAction();
        proxy.execute();
 
        assertEquals(numberAction.getNthPrime(), 2);
        
        
        request.setParameter("num", "5");
        
        proxy = getActionProxy("/numCheck");
        numberAction = (NumberAction) proxy.getAction();
        proxy.execute();
 
        assertEquals(numberAction.getNthPrime(), 11);
 }
}


Before running junit test case, make sure your struts.xml is in class path.
Add struts.xml to class path
Right click on the project, go to properties.

Click on Java Build Path, click on “Add Class Folder” and add classes folder to it. “classes folder contains struts.xml.



You are all set to run junit test case.

Right click on the project -> Run As -> Junit Test.










Prevoius                                                 Next                                                 Home

No comments:

Post a Comment