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



i首先没有提及此问题的关键组成部分:我在这里使用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...
}

我的dao层

@Repository
public class UserDaoImplHibernate implements UserDao {
    @Autowired
    private SessionFactory sessionFactory;
    // My methods using sessionFactory & "talking" to the Db via the sessionFactory
}

这是我的测试类

@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...
}

但是,对于我的测试课程,自动启动, userDao总是返回 null ,我刚刚在春季开始进行测试,我有点丢失。欢迎任何指针。


Boris Treukhov的答案之后的最新编辑

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...
}

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

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

预先感谢

如果创建单元测试,则无法使用Spring IOC功能(正如框架设计人员的意图),因为您是在孤立测试对象(即。测试完成所需的接口)。在这种情况下,您应该手动注入模拟存储库,例如在@before测试初始化方法中。整个想法是您的类仅取决于接口,因此Spring容器基本上评估要用作接口实现的类最小的依赖集),这就是为什么您手动执行注射的原因。

如果您正在进行集成测试,则应该有一个弹簧IOC容器实例启动并运行,为此,您应该使用Junit(假设您正在使用JUNIT)特定的测试跑者,如Spring Document中所述测试。

因此,回到问题时,您有一个看起来像简单的单元测试到Junit,并且不使用弹簧容器。因此,如果您要使用Spring testContext框架,则应该有

之类的东西
   @RunWith(SpringJUnit4ClassRunner.class)
   @ContextConfiguration(locations={"/path-to-app-config.xml", "/your-test-specific-config.xml"})
   public class UserDaoImplHibernateTests

而不是@Component

update 在testng情况下,我认为应该是(我使用spring依赖注入testng作为参考)

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

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

最新更新