== 单元测试应用示例——测试标签库 == AdSumQueryTag.java是后台查询推广来源统计结果的业务逻辑标签处理程序。[[BR]] {{{ #!java /** * * @author ChenYang * Date: 2012-2-1 */ public class AdSumQueryTag extends BaseTagSupport { private String items; public void setItems(String items) { this.items = items; } @Override public int doStartTag() throws JspException { HttpServletRequest request = this.getHttpServletRequest(); if(StringUtils.isBlank(request.getParameter("gid"))){ throw new RuntimeException("没有选择游戏"); } if(StringUtils.isBlank(request.getParameter("startdate"))){ throw new RuntimeException("没有选择开始时间"); } if(StringUtils.isBlank(request.getParameter("enddate"))){ throw new RuntimeException("没有选择结束时间"); } long gameid = Long.parseLong(request.getParameter("gid")); Date start = null; Date end = null; try { start = DateUtils.parseDate(request.getParameter("startdate"), new String[]{"yyyy-MM-dd"}); String enddate = request.getParameter("enddate"); enddate = enddate + " 23:59:59 999"; end = DateUtils.parseDate(enddate, new String[]{"yyyy-MM-dd HH:mm:ss SSS"}); } catch (ParseException e) { e.printStackTrace(); } AdService adService = this.getBean("adService"); List list = adService.findByCondi(gameid, start, end); this.pageContext.setAttribute(items, list); return Tag.SKIP_BODY; } } }}} 该标签依赖的ApplicationContext对象,可以通过继承AbstractTransactionalJUnit4SpringContextTests获得,HttpServletRequest对象和pageContext对象可以通过Spring测试框架提供的模拟对象来模拟。 测试代码如下: {{{ #!java @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:applicationContext.xml" }) public class AdSumQueryTagTest extends AbstractTransactionalJUnit4SpringContextTests{ @Test public void doStartTag() throws Exception { AdSumQueryTag adSumQueryTag = new AdSumQueryTag(); adSumQueryTag.setApplicationContext(applicationContext); adSumQueryTag.setItems("items"); //模拟HttpServletRequest MockHttpServletRequest request = new MockHttpServletRequest(); //模拟查询条件 request.addParameter("gid", "1"); request.addParameter("startdate", "2012-02-08"); request.addParameter("enddate", "2012-02-08"); //模拟pageContext MockPageContext pageContext = new MockPageContext(); adSumQueryTag.setHttpServletRequest(request); adSumQueryTag.setPageContext(pageContext); adSumQueryTag.doStartTag(); } } }}}