下面開始寫要測(cè)試的action, LoginAction:
import javax.servlet.http.*;
import org.apache.struts.action.*;
import org.apache.struts.util.*;
public class LoginAction extends Action {
public ActionForward execute(ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response) {
String username = ((LoginForm) form).getUsername();
String password = ((LoginForm) form).getPassword();
ActionErrors errors = new ActionErrors();
if ((!username.equals("deryl")) || (!password.equals("radar")))
errors.add("password",new ActionError("error.password.mismatch"));
if (!errors.isEmpty()) {
saveErrors(request,errors);
return new ActionForward(mapping.getInput());
}
HttpSession session = request.getSession();
session.setAttribute("authentication", username);
// Forward control to the specified success URI
return mapping.findForward("success");
}
}
[code]
這里我們接收到包含用戶信息的formbean, 首先得到登錄信息,然后驗(yàn)證是否有效,如果無(wú)效,創(chuàng)建ActionError 信息轉(zhuǎn)到登陸頁(yè)面,如相符,把驗(yàn)證信息保存到session, 然后轉(zhuǎn)到下個(gè)頁(yè)面。
有這些事情我們可以測(cè)試:
(1)LoginForm 工作正常嗎?如果在請(qǐng)求中放入合適的參數(shù)它會(huì)正確的被初始化嗎?
(2)如果用戶名和密碼不匹配,是否適當(dāng)?shù)腻e(cuò)誤信息被保存?是否會(huì)轉(zhuǎn)到登陸頁(yè)面?
(3)如果我們提供正確的登陸信息,可以得到正確的頁(yè)面嗎?可以確定不會(huì)報(bào)錯(cuò)嗎?驗(yàn)證信息被保存到session了嗎?
StrutsTestCase 賦予你測(cè)試所有情況的能力,自動(dòng)為你啟動(dòng)ActionServlet
先來(lái)寫一個(gè)空的test case, 他和 junit 非常相似
[code]
public class TestLoginAction extends MockStrutsTestCase {
public void setUp() { super.setUp(); } // 如果要重寫 setUp(), 則必須顯式調(diào)用super.setUp()
public void tearDown() { super.tearDown(); }
public TestLoginAction(String testName) { super(testName); }
public void testSuccessfulLogin() {}
}
下面正式寫這個(gè)測(cè)試,向testSuccessfulLogin中添加:
(1)指定一個(gè)和struts mapping 相關(guān)聯(lián)的路徑,需要說明的是,ActionServlet 默認(rèn)的搜索WEB-INF下的struts-config.xml, 如果struts-config.xml放在了別的目錄下,要在此之前調(diào)用setConfigFile()
setRequestPathInfo("/login");[code]
(2)通過request 對(duì)象向 formbean 傳遞參數(shù)
[code]
addRequestParameter("username","deryl");
addRequestParameter("password","radar");
(3)讓 Action 執(zhí)行
actionPerform();
該方法將模擬從瀏覽器端訪問 servlet 容器內(nèi)的 LoginAction 的過程,先把請(qǐng)求轉(zhuǎn)發(fā)給 ActionServlet,ActionServlet再把表單數(shù)據(jù)組裝到LoginForm中,把請(qǐng)求轉(zhuǎn)發(fā)給LoginAction
(4)驗(yàn)證轉(zhuǎn)到了正確的頁(yè)面
verifyForward("success");
(5)確認(rèn)驗(yàn)證信息被保存到了session
assertEquals("deryl",(String) getSession().getAttribute("authentication"));
(6)確認(rèn)沒有錯(cuò)誤信息
verifyNoActionErrors();