一。在增加spring的jar包时增加单元测试支持。
二。把applicationContext.xml文件最好放在classpath下
三。测试类继承 AbstractDependencyInjectionSpringContextTests并且要实现如下方法:
protected String[] getConfigLocations() {
// TODO Auto-generated method stub
return new String[]{"classpath:com/bitae/sysmanager/applicationContext.xml"};
}
参考代码:
TestAdminDAO.java
package com.bitae.sysmanager.test;
import java.util.List;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
import com.bitae.po.Admin;
import com.bitae.sysmanager.dao.impl.AdminDAO;
public class TestAdminDAO extends AbstractDependencyInjectionSpringContextTests {
// 通过get/set方法来注入adminDAO
private AdminDAO adminDAO;
public AdminDAO getAdminDAO() {
return adminDAO;
}
public void setAdminDAO(AdminDAO adminDAO) {
this.adminDAO = adminDAO;
}
/**
* 取得spring的applicationContext.xml
*/
protected String[] getConfigLocations() {
return new String[] { "classpath:com/bitae/sysmanager/applicationContext.xml" };
}
/**
* 测试AdminDAO的findAll方法
*
*/
public void testFindAll() {
List list = adminDAO.findAll();
assertNotNull(list);
}
public void testSave(){
Admin admin = new Admin();
admin.setChangPwdAllowed("1");
admin.setLoginName("hanfuhua");
admin.setUserPwd("hanfuhua");
adminDAO.save(admin);
}
}