在appfuse应用架构下用Eclipse进行DAO单元测试:
假设工程根目录为%PROJECT_ROOT%
1、把%PROJECT_ROOT%下build\dao\gen等目录加入工程的“Java构建路径”——“库”中的“构建路径上的jar和类文件夹”列表中,完整的须加入的路径:
<classpathentry kind="lib" path="build/dao/gen"/>
<classpathentry kind="lib" path="build/web/classes"/>
<classpathentry kind="lib" path="build/[webappName]"/>
3、为了支持ant test-dao,修改properties.xml的dao.test.classpath,增加
<fileset dir="${commons.dir}" includes="*.jar"/>
<fileset dir="${osworkflow.dir}" includes="*.jar"/>
测试DAO依赖 mail.properties、database.properties等文件和下列xml文件:
%PROJECT_ROOT%\build\dao\gen\*.hbm.xml
%PROJECT_ROOT%\dao\applicationContext-resources.xml
%PROJECT_ROOT%\build\dao\gen\META-INF\applicationContext-hibernate.xml
下面的代码就可以满足测试DAO的依赖
protected String[] getConfigLocations() {
setAutowireMode(AUTOWIRE_BY_NAME);
return new String [] {"classpath*:/**/dao/applicationContext-*.xml",
"classpath*:META-INF/applicationContext-*.xml","/WEB-INF/applicationContext-resources.xml"};
}
示例代码如下:
BaseDaoTestCase.java
package com.sunrise.psmis.dao;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.MissingResourceException;
import java.util.ResourceBundle;import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;/**
* Base class for running Dao tests.
* @author mraible
*/
public abstract class BaseDaoTestCase extends AbstractTransactionalDataSourceSpringContextTests {
protected final Log log = LogFactory.getLog(getClass());
protected ResourceBundle rb;protected String[] getConfigLocations() {
setAutowireMode(AUTOWIRE_BY_NAME);
return new String [] {"classpath*:/**/dao/applicationContext-*.xml",
"classpath*:META-INF/applicationContext-*.xml","/WEB-INF/applicationContext-resources.xml"};
}
public BaseDaoTestCase() {
// Since a ResourceBundle is not required for each class, just
// do a simple check to see if one exists
String className = this.getClass().getName();try {
rb = ResourceBundle.getBundle(className);
} catch (MissingResourceException mre) {
//log.warn("No resource bundle found for: " + className);
}
}/**
* Utility method to populate a javabean-style object with values
* from a Properties file
* @param obj
* @return Object populated object
* @throws Exception
*/
protected Object populate(Object obj) throws Exception {
// loop through all the beans methods and set its properties from
// its .properties file
Map map = new HashMap();for (Enumeration keys = rb.getKeys(); keys.hasMoreElements();) {
String key = (String) keys.nextElement();
map.put(key, rb.getString(key));
}BeanUtils.copyProperties(obj, map);
return obj;
}
}
GenericDaoTest.java
package com.sunrise.psmis.dao;
import java.lang.reflect.Array;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import com.sunrise.psmis.model.User;
import org.springframework.orm.ObjectRetrievalFailureException;/**
* This class tests the generic Dao and BaseDao implementation.
*/
public class GenericDaoTest extends BaseDaoTestCase {
protected Dao dao;
/**
* This method is used instead of setDao b/c setDao uses autowire byType
* <code>setPopulateProtectedVariables(true)</code> can also be used, but it's
* a little bit slower.
*/
public void onSetUpBeforeTransaction() throws Exception {
dao = (Dao) applicationContext.getBean("dao");
}
public void onTearDownAfterTransaction() throws Exception {
dao = null;
}
/**
* 测试Hql语句
*
*/
public void testGenericHql() {
List list =dao.find("select s.loginCode,s.loginName from SysLogin s");
if(list.size()==0){
System.out.println("没有查找到记录!");
}else{
Object obj=list.get(0);
Field[] fields=obj.getClass().getDeclaredFields();
for(int i=0;i<fields.length;i++){
System.out.print(fields[i].getName()+"\t");
}
System.out.println();
Method[] methods=obj.getClass().getDeclaredMethods();
Map map=new HashMap();
for(int i=0;i<methods.length;i++){
map.put(methods[i].getName().toLowerCase(), methods[i]);
}
for(int i=0;i<list.size();i++){
Object o=list.get(i);
if(o.getClass().isArray()){
System.out.println("is array");
int m=Array.getLength(o);
for(int j=0;j<m;j++){
System.out.print(Array.get(o, j)+"\t");
}
}else{
System.out.println("is not array");
for(int j=0;j<fields.length;j++){
try{
System.out.print(((Method)map.get("get"+fields[j].getName().toLowerCase())).invoke(o, new Object[0])+"\t");
}catch(Exception e){
System.out.print("\t");
}
}
}
System.out.println();
}
}super.assertEquals("不相等", list.size()==0, true);
}/**
* Simple test to verify BaseDao works.
*/
public void testCRUD() {
User user = new User();
// set required fields
user.setUsername("foo");
user.setPassword("bar");
user.setFirstName("first");
user.setLastName("last");
user.getAddress().setCity("Denver");
user.getAddress().setPostalCode("80465");
user.setEmail("[email protected]");
// create
dao.saveObject(user);
assertNotNull(user.getId());
// retrieve
user = (User) dao.getObject(User.class, user.getId());
assertNotNull(user);
assertEquals(user.getLastName(), "last");
// update
user.getAddress().setCountry("USA");
dao.saveObject(user);
assertEquals(user.getAddress().getCountry(), "USA");
// delete
dao.removeObject(User.class, user.getId());
try {
dao.getObject(User.class, user.getId());
fail("User 'foo' found in database");
} catch (ObjectRetrievalFailureException e) {
assertNotNull(e.getMessage());
}
}
}