按照慣例,在實(shí)際項(xiàng)目中我往往會對自己編寫的程序進(jìn)行測試,當(dāng)測試通過后才能將其用于實(shí)戰(zhàn)中,當(dāng)然,編寫單元測試是不可避免的,可以直接清晰的檢驗(yàn)出 我們程序的可靠性、可只執(zhí)行性,從中發(fā)現(xiàn)問題從而得到及時(shí)的解決,這里我談?wù)勎覀冺?xiàng)目里Junit編寫規(guī)范、模板,其中包括對web層、業(yè)務(wù)層的分布單 元測試。
【目錄】
-----1.Struts2Junit實(shí)現(xiàn)Web層單元測試
-----2.SpringJunit實(shí)現(xiàn)業(yè)務(wù)層單元測試
【內(nèi)容】
一、編寫struts2Junit(依賴包:struts2-junit-plugin-2.1.8.jar,junit4,xwork-core- 2.2.1.jar,struts2-core-2.2.3.jar,版本號可以任意struts2版本),我以User為例子,下面是UserWebJunit:
/**
* @author fisher
* @description struts2 單元測試用例模板
*/
public class Struts2JunitTemplate extends StrutsTestCase {
/**
* @description 測試ActionMapping,驗(yàn)證資源是否請求
*/
@Test
public void testGetActionMapping() {
ActionMapping mapping = getActionMapping("/test/testAction.action");
assertNotNull(mapping);
assertEquals("/test", mapping.getNamespace());//驗(yàn)證命名空間
assertEquals("testAction", mapping.getName());//驗(yàn)證Action名稱是否對應(yīng)
}
/**
* @description 創(chuàng)建Action代理,驗(yàn)證請求參數(shù)、頁面跳轉(zhuǎn)
* @throws Exception
*/
@Test
public void testGetActionProxy() throws Exception {
// 在執(zhí)行Action方法之前,對request進(jìn)行請求參數(shù)設(shè)置
request.setParameter("name", "fisher");
ActionProxy proxy = getActionProxy("/test/testAction.action");
assertNotNull(proxy);
proxy.setExecuteResult(false);
@SuppressWarnings("rawtypes")
UserAction action = (UserAction ) proxy.getAction();//通過ActionProxy獲得UserAction實(shí)例
assertNotNull(action);
String result = proxy.execute();//執(zhí)行execute方法,返回結(jié)果
assertEquals(Action.SUCCESS, result);//比對返回結(jié)果是否和UserAction中的執(zhí)行結(jié)果一致
}
}