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

时间:2023-02-05 10:31:23

I test the following DAO with JUnit:

我用JUnit测试以下DAO:

@Repository
public class MyDao {

    @Autowired
    private SessionFactory sessionFactory;

    // Other stuff here

}

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.

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

This is the sessionFactory configuration in Spring:

这是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>

What's wrong? How can I enable autowiring for unit testings too?

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

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"

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

4 个解决方案

#1


26  

Add something like this to your root unit test class:

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

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration

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.

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

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

#2


7  

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

您需要使用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"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

注意:这适用于Spring 2.5.2和Hibernate 3.6.5

#3


6  

Missing Context file location in configuration can cause this, one approach to solve this:

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

  • Specifying Context file location in ContextConfiguration
  • 在ContextConfiguration中指定上下文文件位置

like:

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

More details

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

Reference:Thanks to @Xstian

参考:感谢@Xstian

#4


2  

You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:

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

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

This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.

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

#1


26  

Add something like this to your root unit test class:

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

@RunWith( SpringJUnit4ClassRunner.class )
@ContextConfiguration

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.

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

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

#2


7  

You need to use the Spring JUnit runner in order to wire in Spring beans from your context. The code below assumes that you have a application context called testContest.xml available on the test classpath.

您需要使用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"));
    }
}

Note: This works with Spring 2.5.2 and Hibernate 3.6.5

注意:这适用于Spring 2.5.2和Hibernate 3.6.5

#3


6  

Missing Context file location in configuration can cause this, one approach to solve this:

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

  • Specifying Context file location in ContextConfiguration
  • 在ContextConfiguration中指定上下文文件位置

like:

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

More details

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

Reference:Thanks to @Xstian

参考:感谢@Xstian

#4


2  

You need to add annotations to the Junit class, telling it to use the SpringJunitRunner. The ones you want are:

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

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

This tells Junit to use the test-context.xml file in same directory as your test. This file should be similar to the real context.xml you're using for spring, but pointing to test resources, naturally.

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