Spring + TestNG集成测试,注入带注释的DAO失败

Adr*_* Be 5 testing testng spring spring-annotations

我首先没有提到这个问题的关键组成部分:我在这里使用TestNG.

我有一个执行持久性的DAO层.它作为我的小网络应用程序的一部分工作得很好(我有一个经典的控制器,服务,DAO层设计).如果需要,我可以使用我的XML更新此问题.

我的服务层

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao;

    @Override
    public GoodVibeUserDetails getUser(String username) throws UsernameNotFoundException {

        GoodVibeUserDetails user = userDao.getDetailsRolesAndImagesForUser(username);

        return user;
    }

    // more methods...

}
Run Code Online (Sandbox Code Playgroud)

我的DAO层

@Repository
public class UserDaoImplHibernate implements UserDao {

    @Autowired
    private SessionFactory sessionFactory;

    // My methods using sessionFactory & "talking" to the Db via the sessionFactory
}
Run Code Online (Sandbox Code Playgroud)

这是我的测试类

@Component
public class UserDaoImplHibernateTests{

    @Autowired
    private UserDao userDao;

    private GoodVibeUserDetails user; 

    @BeforeMethod
    public void beforeEachMethod() throws ParseException{
        user = new GoodVibeUserDetails();
        user.setUsername("adrien");
        user.setActive(true);
        // & so on...
    }

    /*
     * When everything is fine - test cases
     */
    @Test
    public void shouldAcceptRegistrationAndReturnUserWithId() throws Exception{
        assertNotNull(userDao) ;
        user = userDao.registerUser(user);
        assertNotNull(user.getId()) ;
    }

    // more test cases...

}
Run Code Online (Sandbox Code Playgroud)

但对于我的测试类,Autowiring,userDao总是返回Null,我只是开始在Spring做测试而且我有点迷失.任何指针都是受欢迎的.


鲍里斯特鲁霍夫回答后的最新编辑

import ...
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.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.junit.Assert.assertNotNull;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/applicationContext.xml")
public class UserDaoImplHibernateTests{

    @Autowired
    @Qualifier("userDao")
    private UserDao userDao;

    private GoodVibeUserDetails user; 

    @BeforeMethod
    public void beforeEachMethod() throws ParseException{
        user = new GoodVibeUserDetails();
        user.setUsername("adrien");
        user.setActive(true);
        // & so on...
    }

    /*
     * When everything is fine - test cases
     */
    @Test
    public void shouldAcceptRegistrationAndReturnUserWithId() throws Exception{
        assertNotNull(userDao) ;
        user = userDao.registerUser(user);
        assertNotNull(user.getId()) ;
    }

    // more test methods...

}
Run Code Online (Sandbox Code Playgroud)

这是我的applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xmlns:tx="http://www.springframework.org/schema/tx" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:p="http://www.springframework.org/schema/p" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd" >


    <!-- the application context definition scans within the base package of the application -->
    <!-- for @Components, @Controller, @Service, @Configuration, etc. -->
    <context:annotation-config />
    <context:component-scan base-package="com.goodvibes" />

    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="/WEB-INF/jdbc.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close" 
        p:driverClassName="${jdbc.driverClassName}" p:url="${jdbc.databaseurl}" 
        p:username="${jdbc.username}" p:password="${jdbc.password}" />


    <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">${jdbc.show_sql}</prop>
                <prop key="hibernate.connection.SetBigStringTryClob">true</prop>
                <prop key="hibernate.jdbc.batch_size">0</prop>
            </props>
        </property>
    </bean>

    <tx:annotation-driven />

    <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    [...]

</beans>
Run Code Online (Sandbox Code Playgroud)

我没有添加repository-config.xml,因为这应该足以访问userDao.我仍然得到userDao等于null.

提前致谢

Bor*_*hov 11

如果您创建单元测试,则Spring IoC功能不可用(因为它是框架设计者的意图),因为您正在单独测试对象(即,您只是模拟测试完成所需的最小接口集).在这种情况下,您应该手动注入模拟存储库,例如在@Before测试初始化​​方法中.整个想法是你的类只依赖于接口,所以基本上Spring容器会评估哪个类用作接口实现,但是当你创建一个单元测试时,你需要严格控制调用哪些接口方法(并且有一个接口方法)最小的依赖集),这就是你手动执行注入的原因.

如果您正在进行集成测试,那么您应该启动并运行Spring IoC容器实例,为此,您应该使用jUnit(假设您使用的是jUnit)特定的测试运行器,如Spring测试文档中所述.

所以,回到这个问题,你看起来像jUnit的简单单元测试,并且没有使用Spring容器.所以,如果你打算使用Spring TestContext框架,你应该有类似的东西

   @RunWith(SpringJUnit4ClassRunner.class)
   @ContextConfiguration(locations={"/path-to-app-config.xml", "/your-test-specific-config.xml"})
   public class UserDaoImplHibernateTests
Run Code Online (Sandbox Code Playgroud)

而不是@Component.

更新 TestNg案例我认为应该是(我使用Spring Dependency Injection和TestNG作为参考)

   @ContextConfiguration(locations={"/path-to-app-config.xml", "/your-test-specific-config.xml"})
   public class UserDaoImplHibernateTests extends AbstractTestNGSpringContextTests
Run Code Online (Sandbox Code Playgroud)

另请参见:集成和单元测试之间有什么区别?