﻿<?xml version="1.0" encoding="utf-8" standalone="yes"?><rss version="2.0" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:trackback="http://madskills.com/public/xml/rss/module/trackback/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/"><channel><title>BlogJava-jinfeng_wang-随笔分类-structs</title><link>http://www.blogjava.net/jinfeng_wang/category/812.html</link><description>G-G-S,D-D-U!</description><language>zh-cn</language><lastBuildDate>Thu, 20 Mar 2008 09:39:09 GMT</lastBuildDate><pubDate>Thu, 20 Mar 2008 09:39:09 GMT</pubDate><ttl>60</ttl><item><title>XDoclet的build.xml写法 zz</title><link>http://www.blogjava.net/jinfeng_wang/archive/2008/03/20/187409.html</link><dc:creator>jinfeng_wang</dc:creator><author>jinfeng_wang</author><pubDate>Thu, 20 Mar 2008 01:52:00 GMT</pubDate><guid>http://www.blogjava.net/jinfeng_wang/archive/2008/03/20/187409.html</guid><wfw:comment>http://www.blogjava.net/jinfeng_wang/comments/187409.html</wfw:comment><comments>http://www.blogjava.net/jinfeng_wang/archive/2008/03/20/187409.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/jinfeng_wang/comments/commentRss/187409.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/jinfeng_wang/services/trackbacks/187409.html</trackback:ping><description><![CDATA[http://gocom.primeton.com/showblogarticle.php?cat_id=all&amp;articleId=&amp;blogId=14478&amp;?PHPSESSID=0d485ace30025757c7b9a22da013c1a0&amp;page=4&amp;PHPSESSID=1370043e8b6d902ac0f6fdc3fe7776a8<br />
<br />
<br />
&nbsp;XDoclet的build.xml写法
<p><br />
</p>
<div>
<ol>
    <li>&lt;?xml version="1.0" encoding="utf-8"?&gt; </li>
    <li>&lt;project name="appgen" default="web-demo" basedir="."&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;property file="build.properties" /&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;path id="xdoclet.classpath"&gt; </li>
    <li>&lt;fileset dir="${lib}"&gt; </li>
    <li>&lt;include name="**/*.jar" /&gt; </li>
    <li>&lt;/fileset&gt; </li>
    <li>&lt;path location="${classes}" /&gt; </li>
    <li>&lt;/path&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;target name="clean"&gt; </li>
    <li>&lt;delete&gt; </li>
    <li>&lt;fileset dir="${gen}"&gt; </li>
    <li>&lt;include name="*.xml" /&gt; </li>
    <li>&lt;/fileset&gt; </li>
    <li>&lt;/delete&gt; </li>
    <li>&lt;/target&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;!-- 这个target可以生成，strutsconfigxml , strutsvalidationxml ,web.xml--&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;target name="web-demo" depends="clean,Spring-service-beans,Spring-action-beans,Spring-dao-beans"&gt; </li>
    <li>&lt;taskdef name="webdoclet" classname="xdoclet.modules.web.WebDocletTask" classpathref="xdoclet.classpath" /&gt; </li>
    <li>&lt;webdoclet destDir="${gen}" mergeDir="${merge}" force="false"&gt; </li>
    <li>&lt;fileset dir="${src}"&gt; </li>
    <li>&lt;include name="**/*Action.java" /&gt; </li>
    <li>&lt;include name="**/*Form.java" /&gt; </li>
    <li>&lt;/fileset&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;strutsconfigxml Version="1.2" destDir="${gen}" validateXML="true"/&gt; </li>
    <li>&lt;strutsvalidationxml destDir="${gen}" /&gt; </li>
    <li>&lt;deploymentdescriptor Servletspec="2.4" destDir="${gen}" /&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;/webdoclet&gt; </li>
    <li>&lt;/target&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;target name="ReplaceConfigFile" depends="web-demo"&gt; </li>
    <li>&lt;copy todir="${webinf}"&gt; </li>
    <li>&lt;fileset dir="${gen}"&gt; </li>
    <li>&lt;include name="struts-config.xml"/&gt; </li>
    <li>&lt;include name="validation.xml"/&gt; </li>
    <li>&lt;include name="action-beans.xml"/&gt; </li>
    <li>&lt;include name="dao-beans.xml"/&gt; </li>
    <li>&lt;include name="service-beans.xml"/&gt; </li>
    <li>&lt;/fileset&gt; </li>
    <li>&lt;/copy&gt; </li>
    <li>&lt;/target&gt; </li>
    <li>&lt;!-- 生成spring的xml文件 --&gt; </li>
    <li>&lt;target name="Spring-service-beans" description="Spring-application-beans"&gt; </li>
    <li>&lt;taskdef name="springdoclet" classname="xdoclet.modules.spring.SpringDocletTask" classpathref="xdoclet.classpath" /&gt; </li>
    <li><span>&lt;springdoclet
    excludedTags="@version,@author,@todo" destDir="gen" verbose="true"
    addedTags="@xdoclet-generated at ${TODAY},@copyright The XDoclet
    Team,@author XDoclet,@version ${version}"&gt; </span></li>
    <li>&lt;fileset dir="src" includes="**/*ServiceImpl.java"/&gt; </li>
    <li>&lt;springxml destinationFile="service-beans.xml" destDir="gen"/&gt; </li>
    <li>&lt;/springdoclet&gt; </li>
    <li>&lt;/target&gt; </li>
    <li>&nbsp;</li>
    <li>&nbsp;</li>
    <li>&lt;!-- 生成spring的xml文件 --&gt; </li>
    <li>&lt;target name="Spring-action-beans" description="Spring-servlet-beans"&gt; </li>
    <li>&lt;taskdef name="springdoclet" classname="xdoclet.modules.spring.SpringDocletTask" classpathref="xdoclet.classpath" /&gt; </li>
    <li><span>&lt;springdoclet
    excludedTags="@version,@author,@todo" destDir="gen" verbose="true"
    addedTags="@xdoclet-generated at ${TODAY},@copyright The XDoclet
    Team,@author XDoclet,@version ${version}"&gt; </span></li>
    <li>&lt;springxml destinationFile="action-beans.xml" destDir="gen"/&gt; </li>
    <li>&lt;fileset dir="src" includes="**/*Action.java"/&gt; </li>
    <li>&lt;/springdoclet&gt; </li>
    <li>&lt;/target&gt; </li>
    <li>&nbsp;</li>
    <li>&nbsp;</li>
    <li>&lt;!-- 生成spring的xml文件 --&gt; </li>
    <li>&lt;target name="Spring-dao-beans" description="Spring-servlet-beans"&gt; </li>
    <li>&lt;taskdef name="springdoclet" classname="xdoclet.modules.spring.SpringDocletTask" classpathref="xdoclet.classpath" /&gt; </li>
    <li><span>&lt;springdoclet
    excludedTags="@version,@author,@todo" destDir="gen" verbose="true"
    addedTags="@xdoclet-generated at ${TODAY},@copyright The XDoclet
    Team,@author XDoclet,@version ${version}"&gt; </span></li>
    <li>&lt;springxml destinationFile="dao-beans.xml" destDir="gen"/&gt; </li>
    <li>&lt;fileset dir="src" includes="**/*DAOIbatis.java"/&gt; </li>
    <li>&lt;/springdoclet&gt; </li>
    <li>&lt;/target&gt; </li>
    <li>&nbsp;</li>
    <li>&lt;/project&gt; </li>
    <li>&nbsp;</li>
</ol>
</div>
<p><br />
＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝</p>
<p><br />
</p>
<div>
<ol>
    <li>/** </li>
    <li>* @spring.bean id="UserDAO" </li>
    <li>* @spring.property name="dataSource" ref="dataSource" </li>
    <li>* @spring.property name="sqlMapClient" ref="sqlMapClient" </li>
    <li>* </li>
    <li>* @author Conan </li>
    <li>* </li>
    <li>*/ </li>
    <li>public class UserDAOIbatis extends BaseDAOIBatis implements UserDAO {....} </li>
</ol>
</div>
<p><br />
</p>
<p>-------------------------------------------</p>
<p><br />
</p>
<div>
<ol>
    <li>/** </li>
    <li>* @spring.bean id="UserService" </li>
    <li>* @spring.property name="userDao" ref="UserDAO" </li>
    <li>* </li>
    <li>* @author Conan </li>
    <li>* </li>
    <li>*/ </li>
    <li>public class UserServiceImpl extends BaseManager implements UserService {...} </li>
</ol>
</div>
<p><br />
<br />
&nbsp;---------------------------------------------</p>
<p><br />
</p>
<div>
<ol>
    <li>/** </li>
    <li>* </li>
    <li>* @struts.action path="/add" name="UserForm" input="/add.jsp" </li>
    <li>* type="org.springframework.web.struts.DelegatingActionProxy" </li>
    <li>* validate="true" scope="request" </li>
    <li>* </li>
    <li>* @struts.action-forward name="success" path="/success.jsp" redirect="true" </li>
    <li>* @struts.action-forward name="failure" path="/failure.jsp" redirect="true" </li>
    <li>* </li>
    <li>* @struts.action-form name="UserForm" </li>
    <li>* </li>
    <li>* @spring.bean </li>
    <li>* name="/add" </li>
    <li>* @spring.property </li>
    <li>* name="userService" </li>
    <li>* ref="UserService" </li>
    <li>* </li>
    <li>*/ </li>
    <li>public final class AddAction extends BaseAction {...} </li>
</ol>
</div>
<p><br />
</p>
<p>------------------------------------------</p>
<p><br />
</p>
<div>
<ol>
    <li>/** </li>
    <li>* @struts.form name="UserForm" </li>
    <li>*/ </li>
    <li>public class UserForm extends BaseForm{ </li>
    <li>&nbsp;</li>
    <li>/** </li>
    <li>* @struts.validator type="required" </li>
    <li>* @struts.validator type="mask" msgkey="error.age" </li>
    <li>* @struts.validator-var name="mask" value="^[0-9]*$" </li>
    <li>*/ </li>
    <li>public void setAge(Integer age) { </li>
    <li>this.age = age; </li>
    <li>} </li>
    <li>&nbsp;</li>
    <li>} </li>
</ol>
</div>
<p><br />
</p>
<p><br />
</p>
<br />
<img src ="http://www.blogjava.net/jinfeng_wang/aggbug/187409.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/jinfeng_wang/" target="_blank">jinfeng_wang</a> 2008-03-20 09:52 <a href="http://www.blogjava.net/jinfeng_wang/archive/2008/03/20/187409.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>XDoclet Spring+Struts HowTo zz</title><link>http://www.blogjava.net/jinfeng_wang/archive/2008/03/20/187406.html</link><dc:creator>jinfeng_wang</dc:creator><author>jinfeng_wang</author><pubDate>Thu, 20 Mar 2008 01:42:00 GMT</pubDate><guid>http://www.blogjava.net/jinfeng_wang/archive/2008/03/20/187406.html</guid><wfw:comment>http://www.blogjava.net/jinfeng_wang/comments/187406.html</wfw:comment><comments>http://www.blogjava.net/jinfeng_wang/archive/2008/03/20/187406.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/jinfeng_wang/comments/commentRss/187406.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/jinfeng_wang/services/trackbacks/187406.html</trackback:ping><description><![CDATA[http://www.logemann.org/day/archives/000148.html<br />
<br />
<br />
<p>For all those out there using Spring together with Struts, i created
a small howTo regarding automatic generation of relevant files,
especially the boring action-servlet-xml file which must be in synch
with your struts-config.xml, at least for all Struts actions which
should be injected by Spring.</p>
<p>Lets start with the Action class:</p>
<table border="1">
    <tbody>
        <tr>
            <td>
            <pre>/**<br />
            * Action to delete a Client<br />
            * Date: 09.02.2005<br />
            * Time: 15:29:15<br />
            *<br />
            * @author Logemann - Logentis e.K. (ml@logentis.de)<br />
            * @version $Id$<br />
            * @struts.action path="clientDelete" validate="false"<br />
            *            type="org.springframework.web.struts.DelegatingActionProxy"<br />
            *            name="emptyform"<br />
            * @struts.action-forward name="back" <br />
            *             path="/clientManager.html" redirect="true"<br />
            * @spring.bean name="clientDelete"<br />
            */<br />
            public class ClientDeleteAction extends Action {<br />
            <br />
            <p>    ClientManager clientManagerService;</p>
            <br />
            <br />
            <p>    /**<br />
            <br />
            * Spring injection<br />
            <br />
            *<br />
            <br />
            * @param clientManagerService clientManagerService<br />
            <br />
            * @spring.property ref="clientManagerService"<br />
            <br />
            */<br />
            <br />
            public void setClientManagerService(ClientManager clientManagerService) {<br />
            <br />
            this.clientManagerService = clientManagerService;<br />
            <br />
            }<br />
            <br />
            [..]<br />
            <br />
            </p>
            </pre>
            <br />
            </td>
        </tr>
    </tbody>
</table>
<p>With this tags, the ant build target outlined below will create a
struts-config.xml and the necessary action-servlet.xml needed by
Spring. Lets see how the target looks:</p>
<table border="1">
    <tbody>
        <tr>
            <td>
            &lt;path id="classpath"&gt;
            <p>        &lt;fileset dir="c:/xdoclet-1.2.2" includes="*.jar"/&gt;<br />
            &lt;fileset dir="c:/j2sdkee1.3.1/lib" includes="*.jar"/&gt;<br />
            &lt;fileset dir="c:/struts/lib" includes="struts.jar"/&gt;<br />
            &lt;/path&gt;</p>
            <p>    &lt;taskdef name="springdoclet" <br />
            classname="xdoclet.modules.spring.SpringDocletTask"<br />
            classpathref="classpath"/&gt;<br />
            <br />
            &lt;taskdef name="webdoclet" <br />
            classname="xdoclet.modules.web.WebDocletTask"<br />
            classpathref="classpath"/&gt;</p>
            <p>   &lt;target name="myTest"&gt;<br />
            &lt;webdoclet destDir="c:\" force="true" verbose="true"&gt;<br />
            &lt;fileset dir="${src.dir}"&gt;<br />
            &lt;include name="**/*Form.java" /&gt;<br />
            &lt;include name="**/*Action.java" /&gt;<br />
            &lt;include name="**/*Servlet.java" /&gt;<br />
            &lt;/fileset&gt;<br />
            &lt;strutsconfigxml version="1.1" validateXml="true"/&gt;<br />
            &lt;/webdoclet&gt;</p>
            <p>        &lt;springdoclet destDir="c:\" verbose="true"&gt;<br />
            &lt;fileset dir="${src.dir}"&gt;<br />
            &lt;include name="**/*Action.java" /&gt;<br />
            &lt;/fileset&gt;<br />
            &lt;springxml destinationFile="action-servlet.xml"/&gt;<br />
            &lt;/springdoclet&gt;<br />
            &lt;/target&gt;<br />
            </p>
            </td>
        </tr>
    </tbody>
</table>
<p>Be sure to modify the classpath definition and the destDir values of
springdoclet and webdoclet to suit your needs. Right now the Spring
task only searches for Actions in order to create action-servlet.xml,
if you also want to create your normal service beans like
ClientManagerService, you should create another springdoclet task and
output things to applicationContext.xml if you like. </p>
<p>But this is mostly users choice, as you know, Spring supports from
one to many bean definition files and its up to you how you want to
have your spring xml world.</p>
<p>This will be created when you run the mentioned target:</p>
<p>(action-servlet.xml)<br />
</p>
<table border="1">
    <tbody>
        <tr>
            <td><br />
            &lt;?xml version="1.0" encoding="UTF-8"?&gt;<br />
            &lt;!DOCTYPE beans PUBLIC<br />
            "-//SPRING//DTD BEAN//EN"<br />
            "http://www.springframework.org/dtd/spring-beans.dtd"&gt;
            <p>&lt;beans<br />
            default-autowire="no"<br />
            default-lazy-init="false"<br />
            default-dependency-check="none"<br />
            &gt;</p>
            <p>  &lt;bean<br />
            name="clientDelete"<br />
            class="de.logentis.versysng.action.clientmanager.ClientDeleteAction"<br />
            &gt;</p>
            <p>    &lt;property name="clientManagerService"&gt;</p>
            <p>      &lt;ref bean="clientManagerService"/&gt;<br />
            &lt;/property&gt;</p>
            <p>  &lt;/bean&gt;</p>
            <p>  &lt;!--<br />
            To include additional bean definitions for Spring in the generated<br />
            application context file, add a file to your XDoclet merge directory<br />
            called spring-beans.xml that contains the &lt;bean&gt;&lt;/bean&gt; markup.<br />
            --&gt;<br />
            &lt;/beans&gt;<br />
            </p>
            </td>
        </tr>
    </tbody>
</table>
<p><br />
(struts-config.xml)<br />
</p>
<br />
&lt;?xml version="1.0" encoding="UTF-8" ?&gt;
<p>&lt;!DOCTYPE struts-config PUBLIC "-//Apache Software
Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"&gt;</p>
<p>&lt;struts-config&gt;</p>
<p>  &lt;!-- ========== Data Sources Definitions =================================== --&gt;<br />
&lt;!--<br />
Define your Struts data sources in a file called struts-data-sources.xml and place<br />
it in your merge directory.<br />
--&gt;</p>
<p>  &lt;!-- ========== Form Bean Definitions =================================== --&gt;<br />
&lt;form-beans&gt;</p>
<p>    &lt;!--<br />
If you have non XDoclet forms, define them in a file called struts-forms.xml and<br />
place it in your merge directory.<br />
--&gt;<br />
&lt;/form-beans&gt;</p>
<p>  &lt;!-- ========== Global Exceptions Definitions =================================== --&gt;<br />
&lt;!--<br />
Define your exceptions in a file called global-exceptions.xml and place<br />
it in your merge directory.<br />
--&gt;</p>
<p>  &lt;!-- ========== Global Forward Definitions =================================== --&gt;<br />
&lt;!--<br />
Define your forwards in a file called global-forwards.xml and place<br />
it in your merge directory.<br />
--&gt;</p>
<p>  &lt;!-- ========== Action Mapping Definitions =================================== --&gt;<br />
&lt;action-mappings&gt;<br />
&lt;action<br />
path="clientDelete"<br />
type="org.springframework.web.struts.DelegatingActionProxy"<br />
name="emptyform"<br />
scope="request"<br />
unknown="false"<br />
validate="false"<br />
&gt;<br />
&lt;forward<br />
name="back"<br />
path="/clientManager.html"<br />
redirect="true"<br />
/&gt;<br />
&lt;/action&gt;</p>
<p> &lt;!-- If you have non XDoclet actions, define them in a file
called struts-actions.xml and place it in your merge directory. --&gt;<br />
&lt;/action-mappings&gt;</p>
<p>   &lt;!-- Define your Struts controller in a file called struts-controller.xml and place it in your merge directory. --&gt;</p>
<p> &lt;!-- Define your Struts message-resources in a file called
struts-message-resources.xml and place it in your merge directory.
--&gt;</p>
<p>   &lt;!-- Define your Struts plugins in a file called struts-plugins.xml and place it in your merge directory. --&gt;</p>
&lt;/struts-config&gt;<br />
<br />
<img src ="http://www.blogjava.net/jinfeng_wang/aggbug/187406.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/jinfeng_wang/" target="_blank">jinfeng_wang</a> 2008-03-20 09:42 <a href="http://www.blogjava.net/jinfeng_wang/archive/2008/03/20/187406.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>StrutsTestCase for JUnit v2.1.3</title><link>http://www.blogjava.net/jinfeng_wang/archive/2005/04/30/3965.html</link><dc:creator>jinfeng_wang</dc:creator><author>jinfeng_wang</author><pubDate>Sat, 30 Apr 2005 05:23:00 GMT</pubDate><guid>http://www.blogjava.net/jinfeng_wang/archive/2005/04/30/3965.html</guid><wfw:comment>http://www.blogjava.net/jinfeng_wang/comments/3965.html</wfw:comment><comments>http://www.blogjava.net/jinfeng_wang/archive/2005/04/30/3965.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/jinfeng_wang/comments/commentRss/3965.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/jinfeng_wang/services/trackbacks/3965.html</trackback:ping><description><![CDATA[URL ： <A href="http://strutstestcase.sourceforge.net/">http://strutstestcase.sourceforge.net/</A><BR><BR>做个标记。<BR><BR><img src ="http://www.blogjava.net/jinfeng_wang/aggbug/3965.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/jinfeng_wang/" target="_blank">jinfeng_wang</a> 2005-04-30 13:23 <a href="http://www.blogjava.net/jinfeng_wang/archive/2005/04/30/3965.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item><item><title>Unit Test Your Struts Applicationby（zz）</title><link>http://www.blogjava.net/jinfeng_wang/archive/2005/03/20/2263.html</link><dc:creator>jinfeng_wang</dc:creator><author>jinfeng_wang</author><pubDate>Sun, 20 Mar 2005 10:21:00 GMT</pubDate><guid>http://www.blogjava.net/jinfeng_wang/archive/2005/03/20/2263.html</guid><wfw:comment>http://www.blogjava.net/jinfeng_wang/comments/2263.html</wfw:comment><comments>http://www.blogjava.net/jinfeng_wang/archive/2005/03/20/2263.html#Feedback</comments><slash:comments>0</slash:comments><wfw:commentRss>http://www.blogjava.net/jinfeng_wang/comments/commentRss/2263.html</wfw:commentRss><trackback:ping>http://www.blogjava.net/jinfeng_wang/services/trackbacks/2263.html</trackback:ping><description><![CDATA[Unit Test Your Struts Applicationby <A href="http://www.onjava.com/pub/au/2000" lid="Lu Jian">Lu Jian</A><BR>09/22/2004<BR clear=all>
<P>Unit testing is an important part of a good development process. Although there are many unit testing frameworks and technologies, such as JUnit, Cactus, EasyMock, HttpUnit, and so on, developers often find that it is difficult to unit test their Struts applications.</P>
<P>
<TABLE cellSpacing=0 cellPadding=8 width=336 align=right border=0>
<TBODY>
<TR>
<TD><!-- dy --><NOSCRIPT>
				<a href="http://ad.doubleclick.net/jump/onjava.ds/jspart;abr=!ie;pos=_jspart;sz=336x280;ord=1251671538?"><img src="http://ad.doubleclick.net/ad/onjava.ds/jspart;abr=!ie;pos=_jspart;sz=336x280;ord=1251671538?" border="0" width="336" height="280" alt="Advertisement" /></a>
				</NOSCRIPT></TD></TR></TBODY></TABLE>This article introduces <A href="http://www.onjava.com/onjava/2004/09/22/examples/strutsut.jar" lid="StrutsUT" fn="strutsut.jar">StrutsUT</A>, a simple extension to the <A href="http://jakarta.apache.org/cactus/index.html" el="http://jakarta.apache.org/cactus/index.html" lid="Cactus">Cactus</A> framework, to help solve this problem. It provides two solutions to unit test Struts applications: a "traditional" solution and one based on AspectJ. Developers can choose either for their convenience.</P>
<P>This article explains the initial idea of Cactus from a developer's point of view and extends this idea further into the Struts domain, which is the core of StrutsUT. The reader should have some knowledge of and experience in Struts framework, JUnit, Cactus, and/or AspectJ.</P>
<H3>An Overview of JUnit and Cactus</H3>
<H4>What is JUnit?</H4>
<P>JUnit is a framework to create and perform unit tests on Java classes. With the help of <I>mock object</I>s and override technology, JUnit can perform unit tests for most Java applications. See References below to learn more about JUnit and mock objects. In this article, I chose <A href="http://www.easymock.org/" lid="EasyMock">EasyMock</A> as the mock object implementation.</P>
<P>Below is a simple Java class with its test case.</P><PRE><CODE><FONT color=#003366>//SimpleClass.java
package unittest.simple;

public class SimpleClass {
    public SimpleClass() {
    }
    
    public String foo(int n) {
        ExternalInf inf = getExternalInf();
        String s = inf.doSomeExtThing(n);
        return "Woo!" + s;
    }
    
    protected ExternalInf getExternalInf() {
        ExternalInf inf = null;
        
        //do some operation to get the interface
        //JNDI call or something else
        return inf;
    }
}

//ExternalInf.java

package unittest.simple;

public interface ExternalInf {
    //return "Great" when n equals 10
    String doSomeExtThing(int n);
} 

//SimpleClassTest.java

package unittest.simple;

import org.easymock.MockControl;

import junit.framework.TestCase;

public class SimpleClassTest extends TestCase {
   protected void setUp() throws Exception {
      super.setUp();
   }

   protected void tearDown() throws Exception {
      super.tearDown();
   }

   //Test foo() method in SimpleClass
   public void testFoo() {
      //define the mock object
      MockControl controller = MockControl.
           createControl(ExternalInf.class);
      final ExternalInf inf = (ExternalInf)
           controller.getMock();
       
      //define the behavior of mock object
      inf.doSomeExtThing(10);
      controller.setReturnValue("Great");
      controller.replay();
        
      //use override technology to bridge from 
      //mock object to the class to be tested
      SimpleClass instance = new SimpleClass() {
         protected ExternalInf getExternalInf() {
            return inf;
         }
      };
        
      //start test
      String result = instance.foo(10);
        
      //do verification between expected result 
      //and actual result
      assertEquals("Woo!Great", result);
        
      //do verification on the mock object
      controller.verify();
   }
}</FONT></CODE></PRE>
<P>In the example above, we use a mock object to simulate the external interface and override the <CODE><FONT color=#003366>getExternalInf</FONT></CODE> method to bridge the mock object to the real class to be tested. It this article, I call these two technologies "traditional unit-test technologies".</P>
<H4>The Problems</H4>
<P>When we look at a web application, we find it is still possible to use mock objects and override technology to do the unit test. But this approach has several limitations:</P>
<UL>
<LI>
<P>It involves a large workload. </P>
<P>We need to mock up the <CODE><FONT color=#003366>HttpServletRequest</FONT></CODE>, <CODE><FONT color=#003366>HttpServletResponse</FONT></CODE>, and <CODE><FONT color=#003366>Session</FONT></CODE> objects. This is a tedious and error-prone task.</P>
<LI>
<P>It is difficult to compare the expected and actual results.</P>
<P>The servlet output is not an object structure, but an output stream that contains a run of strings. It is difficult to compare whether two blocks of HTML documents are "equal" or not.</P></LI></UL>
<H4>Why Cactus?</H4>
<P>The most effective way to solve the first problem is very straightforward. Since all web containers already implement these interfaces, why would we need to mock them? Cactus makes use of the web container's implementation to simplify this job. It uses an "in-container" strategy to extend the JUnit framework to the web container.</P>
<P>Cactus has a two-part unit test framework. One part is the traditional JUnit framework. There is an additional <CODE><FONT color=#003366>WebRequest</FONT></CODE>, which allows user to specify request parameters and add HTTP headers. The other is the "in-container" part, which uses a special servlet to bridge the user-defined <CODE><FONT color=#003366>WebRequest</FONT></CODE> to a real <CODE><FONT color=#003366>HttpServletRequest</FONT></CODE>. It also provides a "join point" to interact with the test case. This join point gives test case writers a chance to add request attributes and session attributes, and call the real class (an <CODE><FONT color=#003366>EJB</FONT></CODE>, <CODE><FONT color=#003366>TagLib</FONT></CODE>, <CODE><FONT color=#003366>Servlet</FONT></CODE>, or <CODE><FONT color=#003366>Filter</FONT></CODE> class) to be tested or forward the <CODE><FONT color=#003366>HttpServletRequest</FONT></CODE> to the real web resource (a specific servlet or JSP page).</P>
<P>Figure 1 shows a high-level view of Cactus' traditional unit-testing architecture.</P>
<P><IMG height=226 alt="Cactus Architecture" src="http://www.onjava.com/onjava/2004/09/22/graphics/archi.gif" width=434><BR><I>Figure 1. The traditional Cactus test case execution flow</I></P>
<P>Cactus also integrates HttpUnit to simplify the result comparison. HttpUnit transfers the HTML document into a <CODE><FONT color=#003366>WebResponse</FONT></CODE> object, which contains all kinds of HTML elements, such as forms, tables, input fields, buttons, and so on. This makes the result comparison much easier.</P>
<P>Refer to <A href="http://jakarta.apache.org/cactus/how_it_works.html" el="http://jakarta.apache.org/cactus/how_it_works.html" lid="How Cactus Works">How Cactus Works</A> to learn more about Cactus.</P>
<P>Below is a simple servlet class with its test case.</P><PRE><CODE><FONT color=#003366>// SimpleServlet.java
package unittest.cactus;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class SimpleServlet extends HttpServlet {
   //Return html document with an enabled button
   //if type param == normal
   //Otherwise, return html document with 
   //disabled button
   protected void doGet(
          HttpServletRequest request,
          HttpServletResponse response) 
          throws ServletException, IOException {
      String attr = request.getParameter("type");
      PrintWriter pw = response.getWriter();
      response.setContentType("text/html");
      pw.print(
        "&lt;html&gt;&lt;head/&gt;&lt;body&gt;");
      pw.print("&lt;form name='form1'&gt;");
      if (attr.equals("normal")) {
         pw.print("&lt;input type=button 
                   name='button1' 
                   value='Click me'/&gt;");
      } else {
          pw.print("&lt;input type=button 
                    name='button1' 
                    value='Click me' 
                    disabled/&gt;");
      }
      pw.print("&lt;/form&gt;");
      pw.print("&lt;/body&gt;&lt;/html&gt;");
   }
} 

//SimpleServletTest.java
package unittest.cactus;

import org.apache.cactus.ServletTestCase;
import org.apache.cactus.WebRequest;

import com.meterware.httpunit.Button;
import com.meterware.httpunit.HTMLElement;
import com.meterware.httpunit.WebResponse;

public class SimpleServletTest 
                        extends ServletTestCase {
    
   public SimpleServletTest(String name) {
      super(name);
   }

   protected void setUp() throws Exception {
      super.setUp();
   }

   protected void tearDown() throws Exception {
      super.tearDown();
   }

   //prepare http request parameters
   //set type parameter to normal
   public void beginDoGet1(WebRequest request) {
      request.addParameter("type", "normal");
   }
    
   //test case 1 for doGet() method 
   //in SimpleServlet
   public void testDoGet1() {
     SimpleServlet servlet = new SimpleServlet();
     try {
        servlet.doGet(request, response);
     } catch (Exception e) {
        fail("Unexpected exception: " + e);
     }
   }

   //compare the result
   public void endDoGet1(WebResponse response) {
      HTMLElement[] elements = null;
      try {
         elements = response.
                  getElementsWithName("button1");
         assertEquals(1, elements.length);
         assertFalse(((Button)elements[0]).
                                   isDisabled());
      } catch (Exception e) {
         fail("Unexpected exception: " + e);
      }
   }

   //prepare http request parameters
   //set type parameter to abnormal
   public void beginDoGet2(WebRequest request) {
      request.addParameter("type", "abnormal");
   }
    
   //test case 2 for doGet() method 
   //in SimpleServlet
   public void testDoGet2() {
      SimpleServlet servlet=new SimpleServlet();
      try {
         servlet.doGet(request, response);
      } catch (Exception e) {
         fail("Unexpected exception: " + e);
      }
   }

   //compare the result
   public void endDoGet2(WebResponse response) {
      HTMLElement[] elements = null;
      try {
         elements = response.
                  getElementsWithName("button1");
         assertEquals(1, elements.length);
         assertTrue(((Button)elements[0]).
                                   isDisabled());
      } catch (Exception e) {
         fail("Unexpected exception: " + e);
      }
   }
}<BR><BR><BR><BR><BR><H3>The Problems With Unit Testing a Struts Application</H3><H4>What is Struts?</H4><P>Struts is a successful web-application framework that uses a central controller to control the page flow. The control logic is represented by the Struts configuration file. Refer to <A href="http://struts.apache.org/" el="http://struts.apache.org" lid="struts.apache.org">struts.apache.org</A> to learn more about Struts.</P><P><BR>Below are a simple Struts configuration file and its related <CODE>Action</CODE> and <CODE>Form</CODE>, as well as its JSP file.</P><PRE><CODE>struts-config.xml

&lt;?xml version="1.0" encoding="ISO-8859-1" ?&gt;
&lt;!DOCTYPE struts-config PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 1.1//EN"
"http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd"&gt;
&lt;struts-config&gt;

  ...
  &lt;form-beans&gt;
    &lt;form-bean 
              name="simpleForm"
              type="unittest.struts.SimpleForm"/&gt;
  &lt;/form-beans&gt;

  &lt;action-mappings&gt;
    &lt;action    
              path="/strutsTest"
              type="unittest.struts.SimpleAction"
              name="simpleForm"
              scope="request"&gt;
     &lt;forward 
              name="succeed" 
              path="/result.jsp"/&gt;
    &lt;/action&gt;
  &lt;/action-mappings&gt;
  ...

&lt;/struts-config&gt;


//SimpleForm.java
package unittest.struts;

import org.apache.struts.action.ActionForm;

public class SimpleForm extends ActionForm {
    String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
} 

//SimpleAction.java
package unittest.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import unittest.simple.ExternalInf;

public class SimpleAction extends Action {

    //Get the name from the form and put it 
    //into request attribute
    public ActionForward execute(
                    ActionMapping mapping,
                    ActionForm form,
                    HttpServletRequest request, 
                    HttpServletResponse response)
                    throws Exception {
        SimpleForm simpleForm = (SimpleForm)form;
        ExternalInf inf = getExternalInf();
        String name = simpleForm.getName();
        if (name == null) {
            name = "anonymous";
        }
        request.setAttribute("name", name + 
                         inf.doSomeExtThing(10));
        return mapping.findForward("succeed");
    }
    
    protected ExternalInf getExternalInf() {
        ExternalInf inf = null;
        //do some operation to get the 
        //external interface
        //Use JNDI operation or something else
        return inf;
    }
} 


//result.jsp

&lt;%@ page contentType=
                "text/html; charset=UTF-8"%&gt;
&lt;%@ taglib uri="/WEB-INF/struts-bean.tld" 
           prefix="bean" %&gt;

&lt;html&gt;
&lt;body&gt;
&lt;form name="form1"&gt;
  The name is &lt;input type="text" name="name" 
          value='&lt;bean:write name="name"/&gt;'/&gt;
&lt;/form&gt;
&lt;/body&gt;
&lt;/html&gt;</CODE></PRE><H4>The Problems</H4><P>Struts separates the view and controller from the old servlet approach. This helps developers to implement each function more clearly, but it presents some problems when doing unit tests. There are two approaches to do unit testing on Struts applications:</P><UL><LI><P><B>Using Cactus to test a single <CODE>Action</CODE> class</B></P><P>It is possible to use Cactus to unit test the <CODE>execute()</CODE> method in the <CODE>Action</CODE> class. Test case writers can continue to use the mock object and override approaches. However, they have to construct the <CODE>ActionMapping</CODE> object by themselves. <CODE>ActionMapping</CODE> is a Struts class that is constructed by Struts itself, according to the content of the Struts configuration file. To ask the test case writers to take on this responsibility is not a good choice.</P><P>Below is a test case for <CODE>SimpleAction</CODE>.</P><PRE><CODE>//SimpleActionTest.java
package unittest.struts;

import org.apache.cactus.ServletTestCase;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.easymock.MockControl;

import unittest.simple.ExternalInf;

public class SimpleActionTest 
                        extends ServletTestCase {

   protected void setUp() throws Exception {
      super.setUp();
   }

   protected void tearDown() throws Exception {
      super.tearDown();
   }

   //test execute() method in SimpleAction
   public void testExecute() {
      //define the mock object
      MockControl controller = MockControl.
                createControl(ExternalInf.class);
      final ExternalInf inf = (ExternalInf)
                            controller.getMock();
        
      //define the behavior of mock object
      inf.doSomeExtThing(10);
      controller.setReturnValue("Great");
      controller.replay();

      //create SimpleAction class
      //use override technology to bridge from 
      //mock object to the class
      //to be tested
      SimpleAction action = new SimpleAction() {
         protected ExternalInf getExternalInf() {
              return inf;
         }
      };
      //prepare the SimpleForm
      SimpleForm form = new SimpleForm();
      form.setName("Dennis");
      //prepare the ActionMapping
      ActionMapping mapping=new ActionMapping();
      mapping.addForwardConfig(new ActionForward(
                                   "succeed", 
                                   "/result.jsp", 
                                   false));
       
      try {
         //do the test
         ActionForward forward=action.execute(
                                       mapping, 
                                       form, 
                                       request, 
                                       response);
         //compare the result
         assertNotNull(forward);
         assertEquals("/result.jsp", 
                      forward.getPath());
         //verify the mock object
         controller.verify();
      } catch (Exception e) {
         fail("Unexpected exception: " + e);
      }
   }
} </CODE></PRE><LI><P><B>Using Cactus for an end-to-end test</B></P><P>In some circumstances, there is a requirement to do an end-to-end test in Struts. For example, there is a test case to test whether a specific button in the response HTML document is disabled or not, via a certain URL. There are many limitations in this kind of test. Because the Struts framework controls the whole flow, from accepting the URL to returning the response, there is no "join point" to interact with the test case. It is impossible to use mock objects and overrides. This presents some difficulties for unit testing the Struts application using external interfaces.</P></LI></UL><P>Both of these approaches have serious limitations. The first approach uses traditional unit test technologies, but has limited scope. It can only test the <CODE>Action</CODE> class, which is only part of the Struts framework. The second approach has a larger scope and provides an end-to-end test solution, but cannot use the traditional unit test technologies. It is very difficult to write test cases without the help of these technologies.<BR><BR><BR><BR></P><H4>A Simple Solution</H4><P>Why not combine the two approaches together? Since Struts has done the job of constructing the <CODE>ActionMapping</CODE> according to the Struts configuration file, it is a good choice to leave the mapping construction job to Struts. What we need to do is just to provide a join point around the <CODE>execute()</CODE> method in the <CODE>Action</CODE> class that is called by Struts. Test case writers can make use of this join point to prepare the <CODE>ActionForm</CODE> and use traditional unit test technologies to prepare an <CODE>Action</CODE> class that uses external interfaces.</P><P><BR clear=all>The idea is to extend the Cactus framework's "in-container" part to interact with the test case <B>two</B> times in the web container. One is called by the Cactus-specific servlet, <I>ServletRedirector</I>, as usual. The other is called by the Struts framework. Because Cactus and Struts are both running in the same JVM/web container, they can interact with the same test case instance. </P><H3>Introducing StrutsUT</H3><P>The solution presented here, <A href="http://www.onjava.com/onjava/2004/09/22/examples/strutsut.jar" lid="StrutsUT" fn="strutsut.jar">StrutsUT</A>, provides such an extension to help unit test Struts applications. Here's how it works:</P><OL><LI><P>A client-side test runner creates the test case instance and initiates it by calling the <CODE>begin()</CODE> method. For each test point <CODE><I>XXX</I></CODE> in the test case, it calls the <CODE>begin<I>XXX</I>()</CODE> method to prepare request parameters and/or request headers.</P><LI><P>The client sends the request to the server-side Cactus redirect servlet.</P><LI><P>The redirect servlet creates the test case instance on the server side according to the information from request, and assigns the <CODE>HttpServletRequest</CODE>, <CODE>HttpServletResponse</CODE>, and <CODE>HttpSession</CODE> to the test case public fields.</P><LI><P>The redirect servlet calls the <CODE>setUp()</CODE> method in the test case to satisfy the test precondition and calls <CODE>test<I>XXX</I>()</CODE> to launch the test process.</P><LI><P>The request is redirected to the Struts <CODE>RequestProcessor</CODE>.</P><LI><P><CODE>RequestProcessor</CODE> uses the same test case instance and calls <CODE>prepareFrom<I>XXX</I>()</CODE> and <CODE>prepareAction<I>XXX</I>()</CODE> to prepare the <CODE>ActionForm</CODE> and <CODE>Action</CODE> instance.</P><LI><P>The <CODE>RequestProcessor</CODE> calls the <CODE>execute()</CODE> method in <CODE>Action</CODE>.</P><LI><P>The <CODE>RequestProcessor</CODE> calls <CODE>endAction<I>XXX</I>()</CODE> method in the test case to do any necessary verification and prepare the next join point, if needed.</P><LI><P>The Struts framework finishes the remaining operations and returns the control flow.</P><LI><P>The Cactus redirect servlet calls the <CODE>tearDown()</CODE> method in the test case to clear the test environment.</P><LI><P>The Cactus redirect servlet finishes the test case invocations.</P><LI><P>The Cactus redirect servlet returns the response to client-side test runner.</P><LI><P>The client-side test runner calls the <CODE>end<I>XXX</I>()</CODE> method in the test case to verify the response for each test point <CODE><I>XXX</I></CODE>, and calls the <CODE>end()</CODE> method to clear the status of the test case.</P></LI></OL><P>Figure 2 shows the StrutsUT test case execution flow. </P><P><IMG height=240 alt="Figure 2" src="http://www.onjava.com/onjava/2004/09/22/graphics/architecture.gif" width=550><BR><EM>Figure 2. StrutsUT test case execution flow</EM></P><P>With StrutsUT, test case writers now can do more in the test case: </P><UL><LI><P>Use <CODE>prepareForm<I>XXX</I>()</CODE> method to prepare the <CODE>ActionForm</CODE>, which will be the argument the <CODE>execute()</CODE> method in the <CODE>Action</CODE> class.</P><LI><P>Use the <CODE>prepareAction<I>XXX</I>()</CODE> method to prepare the <CODE>Action</CODE> instance to be called. </P><LI><P>Use the <CODE>endAction<I>XXX</I>()</CODE> method to do any necessary verification and prepare the next join point, if needed, after calling <CODE>Action</CODE>'s <CODE>execute()</CODE> method.</P></LI></UL><P>Like the extra methods in Cactus' <CODE>ServletTestCase</CODE>--<CODE>begin()</CODE>, <CODE>begin<I>XXX</I>()</CODE>, <CODE>end<I>XXX</I>()</CODE>, <CODE>end()</CODE>, <CODE>setUp()</CODE>, and <CODE>tearDown()</CODE>--it is not mandatory to provide these extra methods. Use them when needed.</P><P>There are two implementations in StrutsUT to satisfy the idea described above.</P><H3>The StrutsUT Traditional Solution</H3><P>In order to insert such a join point within the control flow of Struts, it is necessary to extend Struts' central controller, <CODE>RequestProcessor</CODE>, to interact with the test case. We also have to extend Cactus' test case base class, <CODE>ServletTestCase</CODE>, to add extra information about the test point name and test case instance that will be used by the Struts central controller to call the correct test helper methods on the exact test case instance.</P><P>StrutsUT replaces the Struts central controller, <CODE>RequestProcessor</CODE>, with a subclass called <CODE>StrutsUnitTestRequestProcessor</CODE>, and uses <CODE>StrutsServletTestCase</CODE> to replace Cactus' <CODE>ServletTestCase</CODE> as the test case base class.</P><H4>A Simple Test Case</H4><PRE><CODE>// SimpleStrutsTest.java
package unittest.struts;

import javax.servlet.RequestDispatcher;

import org.apache.cactus.WebRequest;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.easymock.MockControl;
import org.jingle.unittest.struts.*;

import unittest.simple.ExternalInf;

import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebResponse;

public class SimpleStrutsTest 
                  extends StrutsServletTestCase {
   //define the mock object
   MockControl controller = MockControl.
                createControl(ExternalInf.class);

   ExternalInf inf = (ExternalInf) 
                            controller.getMock();

   //make sure call the super.setup() when 
   //override this method
   protected void setUp() throws Exception {
      super.setUp();
   }

   //make sure call the super.tearDown() 
   //when override this method
   protected void tearDown() throws Exception {
      super.tearDown();
   }

   public void beginStrutsTestAction(
                            WebRequest request) {
   }

   //Prepare ActionForm
   public ActionForm prepareFormStrutsTestAction(
                ActionMapping mapping) {
      SimpleForm form = new SimpleForm();
      form.setName("Dennis");
      return form;
   }

   //Prepare the Action
   public Action prepareActionStrutsTestAction(
                         ActionMapping mapping) {
      //define the behavior of mock object
      controller.reset();
      inf.doSomeExtThing(10);
      controller.setReturnValue("Great");
      controller.replay();

      //Use override technology to bridge the 
      //mock object to the class to be tested
      SimpleAction action = new SimpleAction() {
         protected ExternalInf getExternalInf() {
            return inf;
         }
      };
      return action;
   }

   public void testStrutsTestAction() {
      //forward to the action to be tested
      RequestDispatcher rd = this.request
         .getRequestDispatcher("/strutsTest.do");
      try {
         rd.forward(this.request, this.response);
      } catch (Exception e) {
         fail("Unexpected exception: " + e);
      }
   }

   //verify the mock object after the execution 
   //of action
   public ActionResult 
                    endActionStrutsTestAction() {
      controller.verify();
      //continue the struts framework process
      return null; 
   }

   //compare the result html documents
   public void endStrutsTestAction(
                          WebResponse response) {
      try {
         WebForm form = response.getForms()[0];
         assertEquals(
                "DennisGreat", 
                form.getParameterValue("name"));
      } catch (Exception e) {
         fail("Unexpected exception: " + e);
      }
   }
} </CODE></PRE><P><BR><BR></P><H4>How to Write the Test Case</H4><P style="PADDING-RIGHT: 0px; PADDING-LEFT: 0px; FONT-SIZE: 1px; PADDING-BOTTOM: 0px; MARGIN: 0px; PADDING-TOP: 0px"></P><P><BR clear=all><!--  me  -->Here are the key points of how to write the test case.</P><UL><LI><P>Each test case should extend from <CODE>StrutsServletTestCase</CODE>.</P><LI><P>Define a <CODE>public ActionForm prepareForm<I>XXX</I>(ActionMapping)</CODE> method if you want to prepare the <CODE>ActionForm</CODE> instance.</P><!--  sidebar begins  --><!--  don't move sidebars  --><!--  sidebar ends  --><LI><P>Define a <CODE>public Action prepareAction<I>XXX</I>(ActionMapping)</CODE> method if you want to prepare the Action instance.</P><LI><P>Define a <CODE>public ActionResult endAction<I>XXX</I>()</CODE> method if you want to verify the mock object and/or introduce the next join point. The return value of this method is an <CODE>ActionResult</CODE> object that contains a <CODE>String</CODE> attribute. In a real Struts application environment, it is quite possible that the forward of an action is also an action instead of a JSP file. In this circumstance, the return value of this method is used to specify the next join point position. For example, if the return <CODE>ActionResult</CODE> contains the string <CODE>YYY</CODE>, the Struts framework will try to call <CODE>prepareForm<I>YYY</I>()</CODE> and <CODE>prepareAction<I>YYY</I>()</CODE> before calling the next <CODE>Action</CODE>, and call <CODE>endAction<I>YYY</I>()</CODE> after the <CODE>Action</CODE> execution. The next example gives you a more complicated scenario and test case. There are two predefined <CODE>ActionResult</CODE> instances: <CODE>TERMINATE</CODE> and <CODE>CONTINUE</CODE>. <CODE>TERMINATE</CODE> simply terminates the process of Struts and return the control flow. <CODE>CONTINUE</CODE> or <CODE>null</CODE> will continue the Struts operation as usual.</P></LI></UL><H4>A More Complicated Example</H4><P>Change the Struts configuration file to make the <CODE>Action</CODE> forward more complicated.</P><PRE><CODE>//struts-config.xml

    ...
    &lt;action  
              path="/strutsTest"
              type="unittest.struts.SimpleAction"
              name="simpleForm"
              scope="request"&gt;
      &lt;forward 
              name="succeed"              
        <B><I>path="/anotherTest.do"/&gt;
    &lt;/action&gt;

    &lt;action    
              path="/anotherTest"
              type="unittest.struts.AnotherAction"&gt;
      &lt;forward 
              name="succeed"              
              path="/result.jsp"/&gt;
    &lt;/action&gt;  </I></B>
    ...

&lt;/struts-config&gt;</CODE></PRE><P>Introduce an extra <CODE>Action</CODE> into the scenario:</P><PRE><CODE>//AnotherAction.java
package unittest.struts;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import unittest.simple.ExternalInf;

public class AnotherAction extends Action {
   public ActionForward execute(
                    ActionMapping mapping, 
                    ActionForm form,
                    HttpServletRequest request, 
                    HttpServletResponse response)
                    throws Exception {
      String name = (String)request.
                            getAttribute("name");
      ExternalInf inf = getExternalInf();
      request.setAttribute("name", name + 
                          inf.doSomeExtThing(1));
      return mapping.findForward("succeed");
   }

   protected ExternalInf getExternalInf() {
      ExternalInf inf = null;
      //do some operation to get the 
      //external interface
      //Use JNDI operation or something else
      return inf;
   }
} </CODE></PRE><P>Write a new test case to test this complicated scenario:</P><PRE><CODE>//AnotherStrutsTest.java
package unittest.struts;

import javax.servlet.RequestDispatcher;

import org.apache.cactus.WebRequest;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.easymock.MockControl;
import org.jingle.unittest.struts.*;

import unittest.simple.ExternalInf;

import com.meterware.httpunit.WebForm;
import com.meterware.httpunit.WebResponse;

public class AnotherStrutsTest 
                  extends StrutsServletTestCase {
   ...
   //Same as what in SimpleStrutsTest

   //Prepare the AnotherAction
   <B><I>public Action prepareActionAnotherAction(
                         ActionMapping mapping) {
      //define the behavior of mock object
      controller.reset();
      inf.doSomeExtThing(1);
      controller.setReturnValue("Little");
      controller.replay();
      
      //Use override technology to bridge the 
      //mock object to the class to be tested
      AnotherAction action=new AnotherAction() {
         protected ExternalInf getExternalInf() {
            return inf;
         }
      };
      return action;
   }</I></B>
   ...

   //verify the mock object after the execution 
   //of action
   public ActionResult 
                    endActionStrutsTestAction() {
      controller.verify();
      //Introduce next join point "AnotherAction"
      return new <B><I>ActionResult("AnotherAction")</I></B>;
   }    

   //compare the result html documents
   public void endStrutsTestAction(
                          WebResponse response) {
      try {
         WebForm form = response.getForms()[0];
         <B><I>assertEquals(
                 "DennisGreatLittle", 
                 form.getParameterValue("name"));</I></B>
      } catch (Exception e) {
         fail("Unexpected exception: " + e);
      }
   }
} </CODE><BR><BR><BR><BR><BR><BR><BR><H3>StrutsUT AspectJ Solution</H3><P>Compared to the traditional solution, the AspectJ solution is more transparent to the test case writer. There's no extension to the Struts central controller and test case base class, just an added aspect: <CODE>StrutsTestCaseAspect</CODE>. </P><P>Refer to the <A href="http://www.onjava.com/pub/a/onjava/2004/09/22/test-struts.html?page=5#resources" lid="References section">References section</A> at the end of the article to learn more about AspectJ. </P><PRE><CODE>// StrutsTestCaseAspect.java
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.cactus.ServletTestCase;
import org.apache.struts.action.Action;
import org.jingle.unittest.struts.util.*;
import org.jingle.unittest.struts.*;

public aspect StrutsTestCaseAspect {
    
  pointcut setup(ServletTestCase testcase) 
  : execution(protected void org.apache.cactus.ServletTestCase+.setUp())
    &amp;&amp; this(testcase);
    
  pointcut teardown(ServletTestCase testcase) 
  : execution(protected void org.apache.cactus.ServletTestCase+.tearDown())
    &amp;&amp; this(testcase);
    
  pointcut actionExecute(ActionMapping mapping, ActionForm form, 
           HttpServletRequest request, HttpServletResponse response) 
  : execution(public ActionForward org.apache.struts.action.Action+.execute
       (ActionMapping, ActionForm, HttpServletRequest, HttpServletResponse))
    &amp;&amp; args(mapping, form, request, response);
    
  after(ServletTestCase testcase) 
  : setup(testcase) 
    &amp;&amp; (!cflowbelow(setup(ServletTestCase))) 
    &amp;&amp; (!within(org.jingle.unittest.struts.StrutsServletTestCase+)) {
       ... //add extra info about the test point and test case instance
  }
    
  before(ServletTestCase testcase)
  : teardown(testcase) 
    &amp;&amp; (!cflowbelow(teardown(ServletTestCase))) 
    &amp;&amp; (!within(org.jingle.unittest.struts.StrutsServletTestCase+)) {
       ... //clear the extra info
  }
    
  ActionForward around(ActionMapping mapping, 
                       ActionForm form, 
                       HttpServletRequest request, 
                       HttpServletResponse response) throws Exception
  : actionExecute(mapping, form, request, response) 
    &amp;&amp; (!cflowbelow(actionExecute(ActionMapping, 
                                  ActionForm, 
                                  HttpServletRequest, 
                                  HttpServletResponse))) 
    &amp;&amp; if (request.getAttribute(
         StrutsTestCaseConstants.WRAPPER_ACTION_ATTR_NAME) == null) {
      ... //introduce the join points before and after the execution()
          //in Action
  }
}</CODE></PRE><P>There are three pointcuts defined in the aspect: <CODE>setup</CODE>, <CODE>teardown</CODE>, and <CODE>actionExecute</CODE>. </P><UL><LI><P>The <CODE>setup</CODE> pointcut will be captured after the <CODE>setUp()</CODE> method in the test case executes, to save extra information about the test point and test case instance.</P><LI><P>The <CODE>teardown</CODE> pointcut will be captured before <CODE>tearDown()</CODE>'s method execution in the test case, to clear any extra information.</P><LI><P>The <CODE>actionExecute</CODE> pointcut will be captured during the <CODE>execute()</CODE> method's execution in the <CODE>Action</CODE> class to introduce join points.</P></LI></UL><H4>A Simple Test Case</H4><P>The <CODE>AspectsimpleStrutsTest</CODE> is almost the same as <CODE>SimpleStrutsTest</CODE> used in the traditional solution, except that it extends the <CODE>ServletTestCase</CODE> defined in the Cactus framework, instead of <CODE>StrutsServletTestCase</CODE> (provided by StrutsUT).</P><PRE><CODE>// AspectSimpleStrutsTest.java
package unittest.struts;

...
public class AspectSimpleStrutsTest extends ServletTestCase {
    ... //same as SimpleStrutsTest
}</CODE></PRE><H4>How to Write the Test Case</H4><P>Writing test cases in the AspectJ solution is similar to how you write them in the traditional solution, except for the first rule: each test case should extend from the <CODE>ServletTestCase</CODE> defined in Cactus framework.</P><P>The more complicated test case in the AspectJ solution, <CODE>AspectAnotherStrutsTest</CODE>, is also available in the sample code package.</P><H3>How to Install StrutsUT</H3><P>Here are the steps to install StrutsUT:</P><UL><LI><P>Prepare the web container. It can be Tomcat, JBoss, or another web container product.</P><LI><P>Install the Struts framework into your web container.</P><LI><P>Install Cactus into your web container.</P><LI><P>Copy <I>StrutsUT.jar</I> into your web application <I>lib</I> directory: <CODE>%CONTEXT_PATH%/WEB-INF/lib</CODE>.</P><LI><P>If you're using mocks, copy <I>easymock.jar</I> into the web application <I>lib</I> directory.</P><LI><P>If you're using the StrutsUT traditional solution, modify the Struts configuration file (it is most likely named <I>struts-config.xml</I>) in <CODE>%CONTEXT_PATH%/WEB-INF</CODE>. Search for the following lines in the file:</P><PRE><CODE>&lt;controller processorClass="org.apache.struts.action.RequestProcessor"
&lt;/controller&gt;</CODE></PRE><P>And replace that with:</P><PRE><CODE>&lt;controller processorClass="org.jingle.unittest.struts.StrutsUnitTestRequestProcessor"
&lt;/controller&gt;</CODE></PRE><P>If you're using the Tiles plug-in with Struts, replace the following lines:</P><PRE><CODE>&lt;controller
    processorClass="org.apache.struts.tiles.TilesRequestProcessor"
&lt;/controller&gt;</CODE></PRE><P>with:</P><PRE><CODE>&lt;controller
    processorClass="org.jingle.unittest.struts.TilesUnitTestRequestProcessor"
&lt;/controller&gt;</CODE></PRE><LI><P>If you're using the StrutsUT AspectJ solution, extract <I>StrutsTestCaseAspect.java</I> from the StrutsUT .jar file and compile with your source code and test cases using the AspectJ compiler.</P></LI></UL><P>Now, the test case is ready to be launched by the JUnit test runner.</P><H3>Conclusion</H3><P>Struts is a widely used framework for web applications. Cactus is a web application unit-test framework. They are two sharp weapons for web application developers, but there are some limitations when unit testing Struts applications using Cactus. StrutsUT provides two solutions to solve this problem by introducing a join point into the Struts execution flow. The traditional solution extends the Struts Request Processor and Cactus test-case base class. The AspectJ solution keeps the Cactus and Struts framework untouched but acquires the source code and test cases compiled with the AspectJ compiler. In the future, this limitation will be removed if the AspectJ compiler supports runtime weaving.</P><H3><A name=resources>References</A></H3><UL><LI><A href="http://www.onjava.com/onjava/2004/09/22/examples/strutsut.jar" lid="Download StrutsUT" fn="strutsut.jar">Download StrutsUT</A> <LI><A href="http://www.onjava.com/onjava/2004/09/22/examples/samples.jar" lid="Download the sample code in this article" fn="samples.jar">Download the sample code in this article</A> <LI><A href="http://www.junit.org/index.htm" lid="JUnit">JUnit</A> <LI><A href="http://www.easymock.org/" lid="EasyMock">EasyMock</A> <LI><A href="http://jakarta.apache.org/cactus/index.html" el="http://jakarta.apache.org/cactus/index.html" lid="Cactus">Cactus</A> <LI><A href="http://struts.apache.org/" el="http://struts.apache.org" lid="Struts">Struts</A> <LI><A href="http://httpunit.sourceforge.net/" el="http://httpunit.sourceforge.net" lid="HttpUnit">HttpUnit</A> <LI><A href="http://www.sys-con.com/story/print.cfm?storyid=45834" lid="Using Apache Cactus">Using Apache Cactus</A> <LI><A href="http://eclipse.org/aspectj" el="http://eclipse.org/aspectj" lid="AspectJ">AspectJ</A> </LI></UL><P><I><A href="http://www.onjava.com/pub/au/2000" lid="Lu Jian">Lu Jian</A> is a senior Java architect/developer with four years of Java development experience. </I></P><BR></PRE></FONT></CODE></PRE><img src ="http://www.blogjava.net/jinfeng_wang/aggbug/2263.html" width = "1" height = "1" /><br><br><div align=right><a style="text-decoration:none;" href="http://www.blogjava.net/jinfeng_wang/" target="_blank">jinfeng_wang</a> 2005-03-20 18:21 <a href="http://www.blogjava.net/jinfeng_wang/archive/2005/03/20/2263.html#Feedback" target="_blank" style="text-decoration:none;">发表评论</a></div>]]></description></item></channel></rss>