13.6. Testing Your Actions with Mock Objects

Problem

You want to unit test your Struts actions without running the application on an application server.

Solution

Use the StrutsTestCase framework to create a unit test, extending the StrutsTestCase MockStrutsTestCase base class, which verifies that your action does what it's supposed to do.

Discussion

The StrutsTestCase framework (http://strutstestcase.sourceforge.net), a JUnit extension, specifically targets the testing of Struts actions. You can download StrutsTestCase from http://strutstestcase.sourceforge.net. If you are coding to the Servlet 2.2 specification, download the binary for 2.2, strutstest212_1.1-2.2.zip; for Servlet 2.3 or later, download strutstest212_1.1-2.3.zip. You should also download the source code for StrutsTestCase; when you need to use a debugger, you can step into the StrutsTestCase code. Unzip the binary and source zip files into a directory.

Copy the strutstest-2.1.2.jar to a location on your application's classpath. Separate your test source code, classes, and libraries from the rest of your application code. You should create a test directory for the application that contains the following:

  • A src folder your test source code

  • A classes folder to compile the test source into

  • A lib folder containing test-specific JAR files such as the StrutsTestCase Jar

When testing, place the test/classes directory and the JAR files in your test/lib directory on your classpath. When you build the actual distribution for your application ...

Get Jakarta Struts Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.