Struts2+Spring + hibernate 中对action的单元测试环境搭建
网上都说没有必要对action进行单元测试,但是有的项目中没有为了代码结构刻意去弄一个service层出来调用dao,而是在action中直接操作Dao层的函数,就我做的这个项目,搭建了一个对antion的单元测试。仅作为备忘。 1.途中碰到的问题。
?
如何来测试action?网上给出的很多参考使用MockStrutsTestCase,而且还是对应struts1.x的。在apache上查看struts2的文档时候发现,有提供一个包struts2-junit-plugin-2.1.8.jar,里面有测试struts2.x中action的类StrutsSpringTestCase,可以用来测试ssh中的action。
?
如何来解决JPA中的lazy机制?大家知道,ssh集成后,hibernate的lazy机制成为让人头疼的问题,网上普遍有两种解决方案,在web.xml中使用spring提供的 OpenSessionInViewFilter来实现,还有一种是在application.xml中配置OpenSessionInViewFilter来实现。前者通用,后者只能用在springmvc结构中。
这里不再详细描述,详见网友blog(http://blog.csdn.net/zxq1406spys/archive/2009/10/30/4748283.aspx)
?
如何来做用户session管理?比如测试跟登陆用户身份信息相关的action。在StrutsSpringTestCase中有request属性,所以我们可以mock出session来代替网页请求的真实session。
2.上述问题解决以后,我们的单元测试环境就可以开始搭建了。 环境描述:Struts2 + Spring2.5 + hibernate3 + junit4 目的:对后台Action层的函数进行单元测试
需要的Jar包:junit4.jar(eclipse自带的,在项目路径中导入即可。“properties->Add Library->JUnit->JUnit4”) struts2-junit-plugin-2.1.8.jar 下面是基础代码
代码
public class MessageActionTest extends StrutsSpringTestCase {
/*这个函数相当@Before注解的函数,是调用单元测试后的时候, 首先会执行的方法。可以在这里面做一些必要的准备工作*/
@Override
protected void setUp() throws Exception { super.setUp(); }
/*这个是单元测试的方法,一个方法测试一个功能,或者一个action*/ @Test
public void testGetReceiveMessage() throws Exception { /*request是类StrutsSpringTestCase的成员变量,
是MockHttpServletRequest对象,在这里mock出来的一个web中的request*/
request.setParameter(\
/*我的环境中,返回值是json格式,result将是json格式的一个字符串
输入action的地址*/
String result = executeAction(\ageAction!getReceiveMessage.action\
//TODO:接下去可以对返回值做分析判断 } }
解决问题jpa中lazy加载的问题,首先在setUp()函数中加入下述代码
代码
SessionFactory sessionFactory = lookupSessionFactory(request);
Session hibernateSession= getSession(sessionFactory); TransactionSynchronizationManager.bindResource(sessionFactory,
new SessionHolder(hibernateSession));
然后再类中加入下面两个私有函数
代码
private Session getSession(SessionFactory sessionFactory) throws DataAccessResourceFailureException {
Session session = SessionFactoryUtils.getSession(sessionFactory, true);
FlushMode flushMode = FlushMode.NEVER; if (flushMode != null) {
session.setFlushMode(flushMode); }
return session; }
private SessionFactory lookupSessionFactory(HttpServletRequest request) {
//“sessionFactory”是你spring配置文件(通常是application.xml)中的SessionFactory。
//如:org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
return (SessionFactory)this.applicationContext.getBea
Struts2+Spring + hibernate 中对action的单元测试环境搭建



