spring继承JUnit

来源:互联网 发布:java定义数组长度 编辑:程序博客网 时间:2024/05/24 05:46

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*:是一种特殊的前缀,指定匹配该前缀后面名字的所有类路径资源都应该被获取。