问题描述
我使用 JUnit 测试以下 DAO:
I test the following DAO with JUnit:
@Repository
public class MyDao {
@Autowired
private SessionFactory sessionFactory;
// Other stuff here
}
如您所见,sessionFactory 是使用 Spring 自动装配的.当我运行测试时, sessionFactory 保持为 null 并且我得到一个空指针异常.
As you can see, the sessionFactory is autowired using Spring. When I run the test, sessionFactory remains null and I get a null pointer exception.
这是 Spring 中的 sessionFactory 配置:
This is the sessionFactory configuration in Spring:
<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>
怎么了?我如何也为单元测试启用自动装配?
What's wrong? How can I enable autowiring for unit testings too?
更新:我不知道这是否是运行 JUnit 测试的唯一方法,但请注意,我在 Eclipse 中运行它,右键单击测试文件并选择运行方式"->JUnit 测试"
Update: I don't know if it's the only way to run JUnit tests, but note that I'm running it in Eclipse with right-clicking on the test file and selecting "run as"->"JUnit test"
推荐答案
将这样的内容添加到您的根单元测试类:
Add something like this to your root unit test class:
@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration
这将使用默认路径中的 XML.如果您需要指定一个非默认路径,那么您可以为 ContextConfiguration 注释提供一个 location 属性.
This will use the XML in your default path. If you need to specify a non-default path then you can supply a locations property to the ContextConfiguration annotation.
http://static.springsource.org/spring/docs/2.5.6/reference/testing.html
这篇关于Spring 不会在使用 JUnit 的单元测试中自动装配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!