按照惯例,在实际项目中我往往会对自己编写的程序进行测试,当测试通过后才能将其用于实战中,当然,编写单元测试是不可避免的,可以直接清晰的检验出 我们程序的可靠性、可只执行性,从中发现问题从而得到及时的解决,这里我就谈谈我们项目里Junit编写规范、模板,其中包括对web层、业务层的分布单 元测试。
【目录】
-----1.Struts2Junit实现Web层单元测试
-----2.SpringJunit实现业务层单元测试
【内容】
一、编写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,验证资源是否请求 */ @Test public void testGetActionMapping() { ActionMapping mapping = getActionMapping("/test/testAction.action"); assertNotNull(mapping); assertEquals("/test", mapping.getNamespace());//验证命名空间 assertEquals("testAction", mapping.getName());//验证Action名称是否对应 } /** * @description 创建Action代理,验证请求参数、页面跳转 * @throws Exception */ @Test public void testGetActionProxy() throws Exception { // 在执行Action方法之前,对request进行请求参数设置 request.setParameter("name", "fisher"); ActionProxy proxy = getActionProxy("/test/testAction.action"); assertNotNull(proxy); proxy.setExecuteResult(false); @SuppressWarnings("rawtypes") UserAction action = (UserAction ) proxy.getAction();//通过ActionProxy获得UserAction实例 assertNotNull(action); String result = proxy.execute();//执行execute方法,返回结果 assertEquals(Action.SUCCESS, result);//比对返回结果是否和UserAction中的执行结果一致 } } |