1 建立基類
public abstract class BaseDaoTestCase extends AbstractTransactionalSpringContextTests {
protected final Log log = LogFactory.getLog(getClass());
protected ResourceBundle rb;
protected String[] getConfigLocations() {
setAutowireMode(AUTOWIRE_BY_NAME);
return new String[] {
"classpath*:/applicationContext-resources.xml",
"classpath*:/META-INF/aop/**/applicationContext-aop*.xml",
"classpath*:/META-INF/dao/**/applicationContext-dao*.xml" };
}
public BaseDaoTestCase() {
// Since a ResourceBundle is not required for each class, just
// do a simple check to see if one existSku
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
* the model object to populate
* @return Object populated object
* @throws Exception
* if BeanUtils fails to copy properly
*/
protected Object populate(Object obj) throws Exception {
// loop through all the beans methods and set its properties from
// its .properties file
Map<String, String> map = new HashMap<String, String>();
for (Enumeration<String> keys = rb.getKeys(); keys.hasMoreElements();) {
String key = keys.nextElement();
map.put(key, rb.getString(key));
}
BeanUtils.copyProperties(map, obj);
return obj;
}
/**
* Create a HibernateTemplate from the SessionFactory and call flush() and
* clear() on it. Designed to be used after "saveSku" methods in tests:
* http://issues.appfuse.org/browse/APF-178.
*/
protected void flush() {
HibernateTemplate hibernateTemplate = new HibernateTemplate(
(SessionFactory) applicationContext.getBean("sessionFactory"));
hibernateTemplate.flush();
hibernateTemplate.clear();
}
}
2 建立需要測試的類,並且繼承1(BaseDaoTestCase .java)
public class DecEnterpriseDaoHibernateTest extends BaseDaoTestCase {
private DecEnterpriseDaoHibernate dao;
public void setDecEnterpriseDao(DecEnterpriseDaoHibernate dao) {
this.dao = dao;
}
@Test
public void testFind() throws DAOException {
DecEnterpriseDto dto = new DecEnterpriseDto();
List list = null;
list = dao.findDecEnterpriseListByDto(dto);
System.out.println("sssss:" + list.size());
}
}
其中classpath*:是一種特殊的首碼,指定匹配該首碼後面名字的所有類路徑資源都應該被擷取。