使用JUnit在struts+spring+hibernate框架环境下进行单元测试
过往使用的方式从最原始的IDE的DEBUG工具断点查错到目前还在用最快捷的使用文字输出(log或system.out)。
这些调试方式不是说不好,但有些情况下达不到自己的需求,浪费了一些时间,因为在SSH的环境下修改的源码就意味着要部署。
有个误区,有的人认为把ApplicationServer的热部署方式设置为ture,就不用部署了。其实实际还是重新部署了一遍,只是不需要你按键罢了。
而且这样的后果还是你每保存一下就帮你部署一次,项目大的话花费很更多,我想也有不少人知道有个内存溢出的问题...挺头痛的..
之前偶尔接触到JUnit,才领略到单元测试的精辟,记录一下学习心得。请别笑学得晚,最近也有个TestNG,有时间也继续研究下。学习调试程序也是一门学问啊。
好啦,言归正传并且长话短说。
使用JUnit进行单元测试方法,初步介绍。
导入JUnit的包就不多说了,一般的IDE都集成的了。
首先建议大家如果想使用Main静态方法来进行调试的话,请直接使用JUnit吧。使用方法很简单,如下:
@Test public void test1() { System.out.println("Hello World!"); } private IMailboxDAO MailboxDAOImpl; @Before public void init() { ApplicationContext context = new ClassPathXmlApplicationContext( new String[] { "applicationContext.xml" }); BeanFactory factory = (BeanFactory) context; MailboxDAOImpl = (IMailboxDAO) factory.getBean("mailboxDAOImpl"); } @Test publiv void testSave(){ Bean transientInstance = new Bean(); ... MailboxDAOImpl.save(transientInstance); } /** * 加载模拟容器 * @throws java.lang.Exception */ @Before public void setUp() throws Exception { super.setUp(); File context = new File("WebRoot"); setContextDirectory(context); } public void testToPageGoMembershipByDl() { String actionUri = "/distributionList/bin/get_members"; String parameterKey1 = "toPage"; String parameterKey2 = "dlId"; String toPageGoStr = "1"; String dlId = "402881b6200d287101200d69838f0009"; Map<String, Object> urlMap = new HashMap<String, Object>(); urlMap.put(parameterKey1, toPageGoStr); urlMap.put(parameterKey2, dlId); generateRequestParameters(urlMap); setRequestPathInfo(actionUri);//设置request的请求 actionPerform();//执行请求 } //公共方法,封装url的parameters请求 public void generateRequestParameters(Map<String, Object> parameters) { if ((parameters != null) && (!parameters.isEmpty())) { for (Map.Entry<String, Object> entry : parameters.entrySet()) { String key = entry.getKey(); Object value = entry.getValue(); String[] parameterValues = null; if (value instanceof String) { parameterValues = new String[] { (String) value }; } else if (value instanceof String[]) { parameterValues = (String[]) value; } if (parameterValues != null) addRequestParameter(key, parameterValues);//增加request参数 } } }