junit测试的一点心得
相信大家都使用junti进行测试过,没使用过也没关系因为这篇文章内容和题目其实没什么关系,呵呵,只是在用junit时发现了一点小问题。 在用junit测试由spring托管的程序时,有时会加载一些外部文件例如如下配置<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="BlogPU" />
<property name="persistenceXmlLocation" value="persistence.xml" />
</bean>
persistence.xml就是外部文件,还有例如hibernate的配置文件,ibatis的,sping自身的等等,如果把spring上下文文件和这些配置文件放到一个目录下的时候,在使用junit加载spring上下文时会报文件找不到,当然一些朋友采取了其他的方法例如写能够让junit找到的相对路径,但是这样的话做为web应用发布的时候又找不到了,多么让人郁闷的一件事啊,我想出一个两全齐美的办法,那就是自己实现目标类的set方法
继承负责加载文件的类
public class SpringLocalContainerEntityManagerFactoryBean extends
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean {
public void setPersistenceXmlLocation(String persistenceXmlLocation) {
String file = SpringLocalContainerEntityManagerFactoryBean.class
.getClassLoader().getResource(persistenceXmlLocation).getFile();
super.setPersistenceXmlLocation(file);
}
}
重新配置
<bean id="entityManagerFactory"
class="com.syj.blog.domain.spring.SpringLocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="BlogPU" />
<property name="persistenceXmlLocation" value="persistence.xml" />
</bean>
这样无论是junit还是web应用就都可以找到了。
页:
[1]