您的位置:軟件測試 > 開源軟件測試 > 開源單元測試工具 > junit
用StrutsTestCase測試Struts
作者:網(wǎng)絡轉(zhuǎn)載 發(fā)布時間:[ 2013/2/18 14:04:15 ] 推薦標簽:

下面開始寫要測試的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, 首先得到登錄信息,然后驗證是否有效,如果無效,創(chuàng)建ActionError 信息轉(zhuǎn)到登陸頁面,如相符,把驗證信息保存到session, 然后轉(zhuǎn)到下個頁面。

有這些事情我們可以測試:
(1)LoginForm 工作正常嗎?如果在請求中放入合適的參數(shù)它會正確的被初始化嗎?
(2)如果用戶名和密碼不匹配,是否適當?shù)腻e誤信息被保存?是否會轉(zhuǎn)到登陸頁面?
(3)如果我們提供正確的登陸信息,可以得到正確的頁面嗎?可以確定不會報錯嗎?驗證信息被保存到session了嗎?

StrutsTestCase 賦予你測試所有情況的能力,自動為你啟動ActionServlet

先來寫一個空的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() {}

}


下面正式寫這個測試,向testSuccessfulLogin中添加:
(1)指定一個和struts mapping 相關(guān)聯(lián)的路徑,需要說明的是,ActionServlet 默認的搜索WEB-INF下的struts-config.xml, 如果struts-config.xml放在了別的目錄下,要在此之前調(diào)用setConfigFile()
setRequestPathInfo("/login");[code]
(2)通過request 對象向 formbean 傳遞參數(shù)
[code]
addRequestParameter("username","deryl");
addRequestParameter("password","radar");

(3)讓 Action 執(zhí)行
actionPerform();

該方法將模擬從瀏覽器端訪問 servlet 容器內(nèi)的 LoginAction 的過程,先把請求轉(zhuǎn)發(fā)給 ActionServlet,ActionServlet再把表單數(shù)據(jù)組裝到LoginForm中,把請求轉(zhuǎn)發(fā)給LoginAction
(4)驗證轉(zhuǎn)到了正確的頁面
verifyForward("success");

(5)確認驗證信息被保存到了session
assertEquals("deryl",(String) getSession().getAttribute("authentication"));

(6)確認沒有錯誤信息
verifyNoActionErrors();

上一頁123下一頁
軟件測試工具 | 聯(lián)系我們 | 投訴建議 | 誠聘英才 | 申請使用列表 | 網(wǎng)站地圖
滬ICP備07036474 2003-2017 版權(quán)所有 上海澤眾軟件科技有限公司 Shanghai ZeZhong Software Co.,Ltd