現(xiàn)在TestLoginAction 是這樣:
import servletunit.struts.*;
public class TestLoginAction extends MockStrutsTestCase {
public TestLoginAction( String testName ){ super( testName ); }
public void testSuccessfulLogin() {
setRequestPathInfo( "/login" );
addRequestParameter( "username", "deryl" );
addRequestParameter( "password", "radar" );
actionPerform();
verifyForward( "success" );
assertEquals("deryl",(String) getSession().getAttribute("authentication"));
verifyNoActionErrors();
}
}
寫ant,編譯運(yùn)行一下看看測試結(jié)果
為了讓 ant 支持 junit 任務(wù),應(yīng)把 junit.jar 復(fù)制到<ANT_HOME>的lib 下
<project name="strutstest" default="test" basedir=".">
<property name="src.home" value="${basedir}/src"/>
<property name="classes.home" value="${basedir}/war/WEB-INF/classes"/>
<property name="lib.home" value="${basedir}/war/WEB-INF/lib"/>
<target name="compile">
<javac srcdir="${src.home}" destdir="${classes.home}" debug="on">
<classpath>
<fileset dir="${lib.home}">
<include name="*.jar"/>
</fileset>
</classpath>
</javac>
</target>
<target name="test" depends="compile">
<junit printsummary="yes">
<classpath>
<pathelement location="${classes.home}"/>
<fileset dir="${lib.home}">
<include name="*.jar"/>
</fileset>
</classpath>
<formatter type="plain"/>
<test name="TestLoginAction"/>
</junit>
</target>
</project>
運(yùn)行后可以看到一切正常,而且在項(xiàng)目的根目錄下自動(dòng)生成 TEST-TestLoginAction.txt,里面寫著測試結(jié)果,如測試有問題,可在這查看錯(cuò)誤信息
正常的情況已經(jīng)測試通過了,現(xiàn)在來看看錯(cuò)誤的情況,寫一個(gè)testFailedLogin :
public void testFailedLogin() {
//setConfigFile("struts-config.xml");
addRequestParameter( "username", "deryl" );
addRequestParameter( "password", "deryl" );
setRequestPathInfo( "/login" );
actionPerform();
verifyForward( "login" );
verifyActionErrors( new String[]{"error.password.mismatch"} );
}
StrutsTestsCase 的簡單使用我們已經(jīng)看過了,和junit 基本相同,很簡單