spring 环境下 的单元测试 spring3+junit4.8
环境? spring 3 + junit4.8
?
首先引入 junit4.8jar包 ,一般eclipse自带的library里是有的,可以直接引入
spring方面要引入 org.springframework.test-3.0.5.RELEASE.jar包
创建一个basetestcase类
继承AbstractTransactionalDataSourceSpringContextTests
?
public abstract class BaseTestCase extends AbstractTransactionalDataSourceSpringContextTests{
?protected static final Logger log = LoggerFactory.getLogger(BaseTestCase.class);
??? /**
???? * spring配置文件的路径前缀
???? */
??? protected static final String CONFIG_PREFIX = "classpath:conf/spring";
??? /**
???? * 定义默认的Spring Context的主文件路径.
???? */
??? protected static final String DEFAULT_MAIN_CONTEXT = "classpath:conf/spring/applicationContext.xml";
???
??? protected static final String LEADIN_CONTEXT = "classpath:conf/spring/leadinServiceContext.xml";
??? /**
???? * 定义除主文件外所有的Spring Context文件集合的路径.
???? */
??? protected static final String All_CONTEXT = "classpath:conf/spring/*.xml";
/**
???? * @see AbstractTransactionalDataSourceSpringContextTests#getConfigLocations()
???? */
??? @Override
??? protected String[] getConfigLocations() {
??????? // 设置AUTOWIRE_BY_NAME ,因为Spring的测试基类默认为BY_TYPE,在有多个相同类型的Bean时冲突.
??????? // 或者取消setter函数,自行用applicationContext.getBean()来显式查找Bean.
??????? setAutowireMode(AUTOWIRE_BY_NAME);
??????? // 默认载入所有的spring配置的bean,在子类可重载此函数以减少载入的applicaitonContext.xml,加快测试速度.
??????? List<String> contexts = new ArrayList<String>();
??????? contexts.add(DEFAULT_MAIN_CONTEXT);
??????? contexts.add(LEADIN_CONTEXT);
??????? contexts.add("classpath:conf/spring/baseCommonDaoContext.xml");
??????? contexts.add("classpath:conf/spring/baseCommonServiceContext.xml");
??????? contexts.add("classpath:conf/spring/baseContext.xml");
??????? contexts.add("classpath:conf/spring/baseFrameContext.xml");
??????? contexts.add("classpath*:mq-server-bootstrap-config.xml");???????
???????
??????? List<String> neededContexts = Arrays.asList(getNeededConfigLocations());
??????? contexts.addAll(neededContexts);
??????? return contexts.toArray(new String[] {});
??? }
/**
???? * 子类只需重写此方法
???? */
??? protected abstract String[] getNeededConfigLocations();
??? protected Object getBean(String name) {
??????? return applicationContext.getBean(name);
??? }
}
?
测试类KgEnrollDaoTest
public class KgEnrollDaoTest extends BaseTestCase {
?@Autowired
?private KgEnrollTimeDao kgEnrollTimeDao;
?
?@Override
?protected String[] getNeededConfigLocations() {
??????? return new String[] { "classpath:/conf/spring/KgEnrollDaoContext.xml" };
??? }
?
?
?public void testsave(){
??String unitId = "1111";
??String enrollyear = "1111";
??
??int i = kgEnrollTimeDao.checkExists(unitId, enrollyear);
??System.out.println(i);
?}
?
?
}
以上方法可以用来测试service和dao
?getNeededConfigLocations 用来引入需要测试的xml配置文件