This tutorial gives you an overview about the StrutsTestCases extension of JUnit and example how you can use it to test your Struts application.



Similar documents
Author: Sascha Wolski Sebastian Hennebrueder Tutorials for Struts, EJB, xdoclet and eclipse.

Java Server Pages combined with servlets in action. Generals. Java Servlets

Creating Java EE Applications and Servlets with IntelliJ IDEA

Struts Tools Tutorial. Version: M5

Understanding class paths in Java EE projects with Rational Application Developer Version 8.0

Eclipse installation, configuration and operation

Overview. About Interstitial Ads: About Banner Ads: About Offer-Wall Ads: ADAttract Account & ID

Development. with NetBeans 5.0. A Quick Start in Basic Web and Struts Applications. Geertjan Wielenga

DTS Web Developers Guide

In this chapter, we lay the foundation for all our further discussions. We start

Slides prepared by : Farzana Rahman TESTING WITH JUNIT IN ECLIPSE

Implementing the Shop with EJB

To begin, visit this URL:

Tutorial: Building a Web Application with Struts

Web Applications. For live Java training, please see training courses at

The goal with this tutorial is to show how to implement and use the Selenium testing framework.

Specify the location of an HTML control stored in the application repository. See Using the XPath search method, page 2.

2. Follow the installation directions and install the server on ccc

Tutorial for Spring DAO with JDBC

Web Container Components Servlet JSP Tag Libraries

CS506 Web Design and Development Solved Online Quiz No. 01

SDK Code Examples Version 2.4.2

A Practical Guide to Test Case Types in Java

Document Digital Signature

Kepware Technologies KEPServerEX Client Connectivity Guide for GE's Proficy ifix

Developing an EJB3 Application. on WebSphere 6.1. using RAD 7.5

WordCom, Inc. Secure File Transfer Web Application

APPENDIX A: MOCKITO UNIT TESTING TUTORIAL

Getting Started With Delegated Administration

Jolly Server Getting Started Guide

SharePoint Wiki Redirect Installation Instruction

HHC Compensation Module Training Document

SharePoint List Filter Favorites Installation Instruction

TESTING WITH JUNIT. Lab 3 : Testing

Application Security

ContentWatch Auto Deployment Tool

Advanced Digital Imaging

ICP Data Entry Module Training document. HHC Data Entry Module Training Document

Web Applications. Originals of Slides and Source Code for Examples:

Using a Remote SQL Server Best Practices

Creating Home Directories for Windows and Macintosh Computers

CI/CD Cheatsheet. Lars Fabian Tuchel Date: 18.March 2014 DOC:

ID TECH UniMag Android SDK User Manual

Web Service Caching Using Command Cache

Creating a Digital Signature in Adobe Acrobat Created on 1/11/2013 2:48:00 PM

IBM Operational Decision Manager Version 8 Release 5. Getting Started with Business Rules

HIC.SOAP Network User Instructions last updated June 22, :39 AM

EMC Documentum Business Process Suite

Windows: File Management. Lesson Notes Author: Pamela Schmidt

State of Michigan Data Exchange Gateway. Web-Interface Users Guide

Introduction. Before you begin. Installing efax from our CD-ROM. Installing efax after downloading from the internet

Module 11 Setting up Customization Environment

How to develop your own app

Tool Tip. SyAM Management Utilities and Non-Admin Domain Users

Instructions for Configuring a SAS Metadata Server for Use with JMP Clinical

Hello World RESTful web service tutorial

Montefiore Portal Quick Reference Guide

Tutorial: setting up a web application

How To Connect A Java To A Microsoft Database To An Ibm.Com Database On A Microsq Server On A Blackberry (Windows) Computer (Windows 2000) On A Powerpoint (Windows 5) On An Ubio.Com

Project 5 Twitter Analyzer Due: Fri :59:59 pm

HOW TO SILENTLY INSTALL CLOUD LINK REMOTELY WITHOUT SUPERVISION

Rational Application Developer v7.0 (RAD7) trial version. Installation guide

Creating a Java application using Perfect Developer and the Java Develo...

Getting Started with Web Applications

9. Database Management Utility

Junk Settings. Options

JBoss SOAP Web Services User Guide. Version: M5

Capture Pro Software FTP Server System Output

Tutorial: BlackBerry Application Development. Sybase Unwired Platform 2.0

SCUt ils SmartAssign Guide Solution for Microsoft System Center 2012 Service Manager

Building and Using Web Services With JDeveloper 11g

Configuring the BBj Jetty Web Server (rev10.02) for OSAS

Course Name: Course in JSP Course Code: P5

How to setup a network printer using HP Universal Printer Driver

Wilkes University Mail Storage & Housekeeping for Students using Outlook 2003

<Insert Picture Here> Oracle WebCenter Spaces and Oracle BI Applications Configuration

User Management Tool 1.6

Tutorial. Patch Management

ScriptLogic File System Auditor User Guide

How to deploy fonts using Configuration Manager 2012 R2

Generating Open For Business Reports with the BIRT RCP Designer

for Sage 100 ERP Paperless Office Overview Document

CDOT Workflow ProjectWise Web Access Operations

TimeSite & ExpenSite Offline Utility 4.0

You must have at least Editor access to your own mail database to run archiving.

We are not repeating all the basics here. Have a look at the basic EJB tutorials before you start this tutorial.

Tutorial #7A: LC Segmentation with Ratings-based Conjoint Data

In this tutorial I will be uploading multiple images to my ftp folder on my ktools site, and then add them using manager.

Hadoop Basics with InfoSphere BigInsights

Installation Guide of the Change Management API Reference Implementation

Smooks Dev Tools Reference Guide. Version: GA

Installation Guide - Client. Rev 1.5.0

Using Microsoft Visual Studio API Reference

This procedure is used by the Staff Member to certify their monthly time statement.

USING SSL/TLS WITH TERMINAL EMULATION

ThirtySix Software WRITE ONCE. APPROVE ONCE. USE EVERYWHERE. SMARTDOCS SHAREPOINT CONFIGURATION GUIDE THIRTYSIX SOFTWARE

JUnit Automated Software Testing Framework. Jeff Offutt. SWE 437 George Mason University Thanks in part to Aynur Abdurazik. What is JUnit?

Transcription:

Junit Testing with Struts (StrutsTestCases extension) This tutorial gives you an overview about the StrutsTestCases extension of JUnit and example how you can use it to test your Struts application. General Author: Sascha Wolski Sebastian Hennebrueder http://www.laliluna.de/tutorials.html Tutorials for Struts, EJB, xdoclet and eclipse. Date: April, 13 2005 Software: Eclipse 3.x MyEclipse 3.8.x StrutsTestCases for JUnit 2.1.3 Source code: http://www.laliluna.de/assets/tutorials/junit-testing-struts-source-light.zip The sources do not contain any project files of eclipse or libraries. Create a new project following the tutorial, add the libraries as explained in the tutorial and then you can copy the sources in your new project. PDF Version http://www.laliluna.de/assets/tutorials/junit-testing-struts-en.pdf What is StrutsTestCases? StrutsTestCase for JUnit is an extension of the standard JUnit TestCase class that provides capabilities for testing code developed with the Struts framework. StrutsTestCase provides a Mock Object approach and a Cactus approach to actually run the Struts ActionServlet. A Mock Object expects that you are using a running servlet engine. The Cactus approach does not expect a servlet engine. Because StrutsTestCase uses the ActionServlet controller to test your code, you can test not only the implementation of your Action objects, but also your mappings, form beans, and forwards declarations. And because StrutsTestCase already provides validation methods, it's quick and easy to write unit test cases. What is the MockStrutsTestCase? The MockStrutsTestCase use a set of HttpServlet mock objects to simulate the container environment without running a servlet engine. You can test your Struts code without running a application server or deploying your code to a application server. To use the MockStrutsTestCase you have to extend your test classes from the MockStrutsTestCase class. What is the CactusStrutsTestCase? The CactusStrutsTestCase use the Cactus testing framework http://jakarta.apache.org/cactus to test Struts classes in the actual sever container, it is called in-container testing. It use the actual development environment for testing. To use the CactusStrutsCase you have to extend your test classes from the CactusStrutsCase. Note: You can change the approaches by simply subclassing the MockStrutsTestCase or the CactusStrustTestCase without changing another line of your code. The Example We use an existing example, a library application, to write some tests for. You can download the

full source code of the library application with the link below. http://www.laliluna.de/assets/tutorials/junit-testing-struts-source.zip Notice for non MyEclipse User: Have a look at the tutorial http://laliluna.de/first-steps-with-struts-free-tools-en.html to learn how to create a Webproject with free tools. In the example application you can add, edit, delete and list books of a library. We want to test some of this features to make sure that they working correctly. The TestCase If you have downloaded the example application and import it in the Eclipse Workspace first you have to add the JUNIT_HOME variable to the Java-Build-Path of our project. Open the properties dialog of the project, right mouse button on the project and choose Properties. Open the Java-Build-Path section and click on the Add Variable.. button on the right side. Choose the JUNIT_HOME variable of the list. The next step is fit up the application with the StrutsTestCases jar file. Copy the jar file into the lib folder under /WebRoot/WEB-INF and refresh the project tree in the package explorer (Download StrutsTestCases).

Let's start by creating an empty test case, which we extend from the base StrutsTestCase class. First, add a new package test.de.laliluna.tutorial.library Create a new class TestLibrary which extends from the MockStrutsTestCase class of the StrutsTestCases extension. The class is used as a class which extends the TestCase class of the JUnit framework. So you can override the setup() and teardown() method. Note: If you override the setup() method you must explicit call super.setup(). This method performs some important initializations routines, and StrutsTestCases will not work if it is not called. The first thing we do is create a constructor with a parameter testname which calls the super class. public class TestLibrary extends MockStrutsTestCase { public TestLibrary(String testname) { super(testname); We want to write test for the following features of the application: Save a book List all books First of all we have initialize some parameters and an action form. Provide a private property bookeditform of type BookEditForm. public class TestLibrary extends MockStrutsTestCase { private BookEditForm bookeditform; public TestLibrary(String testname) { super(testname); Override the setup() method to initialize some parameter. public void setup() throws Exception { super.setup(); // set the context directory to /WebRoot // to find the /WEB-INF/web.xml setcontextdirectory(new File("WebRoot")); true)); // set the book into the action form bookeditform = new BookEditForm(); bookeditform.setbook(new Book(1, "laliluna", "StrutsTestCases Tutorial", Use the setcontextdirectory(..) method to set the context directory where StrutsTestCases search for the web.xml file, because we use MyEclipse and the web.xml is placed in the /WebRoot/WEB- INF/ folder. (Default is WEB-INF/web.xml) Then create a new instance of the action form class BookEditForm and set the property book.

Test save a book First have a look in the BookEditAction class where you find the method savebook. You will see that a action form is used to get the data of the book which will be saved. After saving the book we will find and return a action forward showlist. The following listing shows the method savebook: public ActionForward savebook( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { BookEditForm bookeditform = (BookEditForm) form; /* lalinuna.de 04.11.2004 * init SimulateDB class and get data by id */ SimulateDB simulatedb = new SimulateDB(); simulatedb.savetodb(bookeditform.getbook(), request.getsession()); return mapping.findforward("showlist"); Create a new method testsavebook in the class TestLibrarty to test if you can add a book without errors. With the method setrequestpathinfo you set the request path for the test case. We need a parameter do which identifies the method which is called by the DispatchAction class BookEditAction. Use the method addrequestparameter to set a parameter and the value. Within the savebook method a action form stores the book which will be saved. We have to set this action form with the method setactionform. Finally we need to get the Action to do its thing. Execute the actionperform method. public void testsavebook() { setrequestpathinfo("/bookedit"); addrequestparameter("do", "savebook"); setactionform(bookeditform); That's all you have to do to get the ActionServlet to process your request. Now we still need to verify that everything happened as we expected it to. First we want to test if the book is added to the collection which is placed in the session. Get the list of books from the session as an ArrayList. The last entry of the list must be the book we have added before, so we test the title of the last entry if it is equal to our title. Then we verify the action forward which is returned by the savebook method of the EditBookAction class. public void testsavebook() { setrequestpathinfo("/bookedit"); addrequestparameter("do", "savebook"); setactionform(bookeditform); ArrayList bookdb = (ArrayList) getsession().getattribute("bookdb"); assertequals("strutstestcases Tutorial", ((Book) bookdb.get(bookdb.size () - 1)).getTitle()); verifyforward("showlist");

In the second scenario we want to test if the BookListAction class works correctly. First have a look to the execute method of the BookListAction class: public ActionForward execute( ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { BookListForm booklistform = (BookListForm) form; /* lalinuna.de 03.11.2004 * init SimulateDB class and set some dummy data */ SimulateDB simulatedb = new SimulateDB(); booklistform.setbooks(simulatedb.getallbooks(request.getsession())); return mapping.findforward("showlist"); Create a new method testbooklist. First we have to set the request path to /booklist. We do not need any other parameter so we can process the request with actionperform. Next we test if the list of books stored in the action form is not null and then we verify the action forward returned by the method execute of the BookListAction class. public void testbooklist(){ setrequestpathinfo("/booklist"); assertnotnull(((booklistform)getactionform()).getbooks()); verifyforward("showlist"); Run the test cases Finally we can run the test cases. Right mouse button on the test class TestLibrary and choose Run > JUnit Test. If all test runs without errors your JUnit tab of MyEclipse looks like the following.