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

时间:2013-07-12 20:41:49

标签: java spring junit

我使用JUnit测试以下DAO:

@Repository
public class MyDao {

    @Autowired
    private SessionFactory sessionFactory;

    // Other stuff here

}

如您所见,sessionFactory使用Spring自动装配。当我运行测试时,sessionFactory保持为null并且我得到一个空指针异常。

这是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” - &gt;“JUnit test “

7 个答案:

答案 0 :(得分:29)

将这样的内容添加到根单元测试类:

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration

这将在默认路径中使用XML。如果需要指定非默认路径,则可以为ContextConfiguration批注提供locations属性。

http://static.springsource.org/spring/docs/2.5.6/reference/testing.html

答案 1 :(得分:8)

我使用的是 JUnit 5,对我来说问题是我从错误的包中导入了 Test

import org.junit.Test;

将其替换为以下对我有用:

import org.junit.jupiter.api.Test;

答案 2 :(得分:7)

您需要使用Spring JUnit运行器,以便从您的上下文连接Spring bean。下面的代码假定您在测试类路径上有一个名为testContest.xml的应用程序上下文。

import org.hibernate.SessionFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.sql.SQLException;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.startsWith;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:**/testContext.xml"})
@Transactional
public class someDaoTest {

    @Autowired
    protected SessionFactory sessionFactory;

    @Test
    public void testDBSourceIsCorrect() throws SQLException {
        String databaseProductName = sessionFactory.getCurrentSession()
                .connection()
                .getMetaData()
                .getDatabaseProductName();
        assertThat("Test container is pointing at the wrong DB.", databaseProductName, startsWith("HSQL"));
    }
}

注意:这适用于 Spring 2.5.2 Hibernate 3.6.5

答案 3 :(得分:6)

配置中缺少上下文文件位置可能导致这种情况,一种方法可以解决这个问题:

  • 在ContextConfiguration中指定上下文文件位置

像:

@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })

更多详情

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration(locations = { "classpath:META-INF/your-spring-context.xml" })
public class UserServiceTest extends AbstractJUnit4SpringContextTests {}

参考:Thanks to @Xstian

答案 4 :(得分:3)

我在Spring Boot 2.1.1和JUnit 4中遇到了相同的问题
刚刚添加了这些注释:

@RunWith( SpringRunner.class )
@SpringBootTest

,一切进展顺利。

对于Junit 5:

@ExtendWith(SpringExtension.class)

source

答案 5 :(得分:2)

您需要向Junit类添加注释,告诉它使用SpringJunitRunner。你想要的是:

@ContextConfiguration("/test-context.xml")
@RunWith(SpringJUnit4ClassRunner.class)

这告诉Junit在测试的同一目录中使用test-context.xml文件。这个文件应该类似于你用于spring的真正的context.xml,但是自然地指向测试资源。

答案 6 :(得分:0)

我也遇到了这个问题,原因是 @Test

的导入无效

删除导入

import org.junit.Test;

并使用

import org.junit.jupiter.api.Test;