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

use*_*212 41 java junit spring

我用JUnit测试以下DAO:

@Repository
public class MyDao {

    @Autowired
    private SessionFactory sessionFactory;

    // Other stuff here

}
Run Code Online (Sandbox Code Playgroud)

如您所见,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>
Run Code Online (Sandbox Code Playgroud)

怎么了?如何为单元测试启用自动装配?

更新:我不知道它是否是运行JUnit测试的唯一方法,但请注意我在Eclipse中运行它,右键单击测试文件并选择"run as" - >"JUnit test"

rob*_*lco 31

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

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration
Run Code Online (Sandbox Code Playgroud)

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

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


Mci*_*cin 18

我在 Spring Boot 2.1.1 和 JUnit 4 中遇到了同样的问题,
只是添加了这些注释:

@RunWith( SpringRunner.class )
@SpringBootTest
Run Code Online (Sandbox Code Playgroud)

一切顺利。

对于 Junit 5:

@ExtendWith(SpringExtension.class)
Run Code Online (Sandbox Code Playgroud)

来源

  • 仍然为空 (12认同)

Can*_*ner 9

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

import org.junit.Test;
Run Code Online (Sandbox Code Playgroud)

用以下内容替换它对我有用:

import org.junit.jupiter.api.Test;
Run Code Online (Sandbox Code Playgroud)


Mik*_*der 8

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

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"));
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:这适用于Spring 2.5.2Hibernate 3.6.5


Abh*_*eet 6

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

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

喜欢:

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

更多细节

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

参考:感谢@Xstian