我用 JUnit 测试了以下 DAO:
@Repository
public class MyDao {
@Autowired
private SessionFactory sessionFactory;
// Other stuff here
}
如您所见,sessionFactory 是使用 Spring 自动装配的。当我运行测试时,sessionFactory 保持为空,我得到一个空指针异常。
这是 Spring 中的 sessionFactory 配置:
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation">
<value>classpath:hibernate.cfg.xml</value>
</property>
<property name="configurationClass">
<value>org.hibernate.cfg.AnnotationConfiguration</value>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${jdbc.dialect}</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
</bean>
怎么了?我怎样才能为单元测试启用自动装配?
更新:我不知道这是否是运行 JUnit 测试的唯一方法,但请注意,我是在 Eclipse 中运行它的,右键单击测试文件并选择“run as”->“JUnit test”
原文由 user1883212 发布,翻译遵循 CC BY-SA 4.0 许可协议
将类似这样的内容添加到您的根单元测试类:
这将在您的默认路径中使用 XML。如果您需要指定一个非默认路径,那么您可以为 ContextConfiguration 注释提供一个位置属性。
http://static.springsource.org/spring/docs/2.5.6/reference/testing.html