Spring不能在使用JUnit的单元测试中自动装配

Spring不能在使用JUnit的单元测试中自动装配

问题描述:

我使用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中右键单击测试文件并选择run as - >JUnit test

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批注提供locations属性。

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