简体   繁体   English

在JUnit for DAO层中找不到当前线程的会话

[英]No Session found for current thread in JUnit for DAO layer

I want to make tests for my DAO methods with JUnit. 我想用JUnit对我的DAO方法进行测试。 I already have defined test class for service layer, but this method dont work for dao. 我已经为服务层定义了测试类,但是此方法不适用于dao。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:hibernate4Config.xml"})
public class UserServiceTest {
    @Autowired
    private SessionFactory sessionFactory;
    @Autowired
    private UserService userService;

    private Session session;


    @Before
    public final void before() {
        session = sessionFactory.openSession();
    }

    @After
    public final void after() {
        session.close();
    }
//tests

When I try to run tests for dao I see No Session found for current thread; nested exception is org.hibernate.HibernateException: No Session found for current thread 当我尝试对dao运行测试时,我看到No Session found for current thread; nested exception is org.hibernate.HibernateException: No Session found for current thread No Session found for current thread; nested exception is org.hibernate.HibernateException: No Session found for current thread

My code from DaoTest class: 我的代码来自DaoTest类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:hibernate4Config.xml"})
public class UserDaoTest {
    @Autowired
    private SessionFactory sessionFactory;
    @Autowired
    private IUserDao userDao;

    private Session session;


    @Before
    public final void before() {
        session = sessionFactory.openSession();
    }

    @After
    public final void after() {
        session.close();
    }
//tests...

I have found that cannot work because I have service classes annoted as @Transactional and @Service. 我发现这行不通,因为我将服务类标注为@Transactional和@Service。 But I need to test DAO layer, any hack for it? 但是我需要测试DAO层,对此有何建议?

My hibernate4config.xml: 我的hibernate4config.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
      http://www.springframework.org/schema/beans
      http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
      http://www.springframework.org/schema/context
      http://www.springframework.org/schema/context/spring-context-4.0.xsd">

    <context:property-placeholder location="classpath:persistence-mysql.properties" />
    <context:component-scan base-package="com.prokopenko.tfc" />

    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="packagesToScan" value="com.prokopenko.tfc.domain" />
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
            </props>
        </property>
    </bean>

    <bean id="dataSource" class="org.apache.tomcat.dbcp.dbcp.BasicDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.user}" />
        <property name="password" value="${jdbc.pass}" />
    </bean>

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


    <bean id="persistenceExceptionTranslationPostProcessor" class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />

</beans>

For DAO I use generics, my abstract superclass - 对于DAO,我使用泛型,即我的抽象超类-

public abstract class AbstractHibernateDao<T extends Serializable> implements IOperations<T> {
    private Class<T> clazz;

    @Autowired
    private SessionFactory sessionFactory;


    protected final void setClazz(final Class<T> clazzToSet) {
        clazz = Preconditions.checkNotNull(clazzToSet);
    }

    @Override
    public final T findOne(final long id) {
        return (T) getCurrentSession().get(clazz, id);
    }

    @Override
    public final List<T> findAll() {
        return getCurrentSession().createQuery("from " + clazz.getName()).list();
    }

    @Override
    public final void create(final T entity) {
        Preconditions.checkNotNull(entity);
        // getCurrentSession().persist(entity);
        getCurrentSession().saveOrUpdate(entity);
    }

    @Override
    public final T update(final T entity) {
        Preconditions.checkNotNull(entity);
        return (T) getCurrentSession().merge(entity);
    }

    @Override
    public final void delete(final T entity) {
        Preconditions.checkNotNull(entity);
        getCurrentSession().delete(entity);
    }

    @Override
    public final void deleteById(final long entityId) {
        final T entity = findOne(entityId);
        Preconditions.checkState(entity != null);
        delete(entity);
    }

    protected final Session getCurrentSession() {
        return sessionFactory.getCurrentSession();
    }

UserDaoImpl annoted with @Repository 用@Repository注释的UserDaoImpl

Well in order for you to test a dao it need to be annotated with 好吧,为了让您测试dao,需要添加注释

@Transactional @Transactional

For there to be a active session to the database. 为了与数据库建立活动会话。 You can include it in your test and it should make your test pass 您可以将其包含在测试中,并且应该可以通过测试

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM