【问题标题】:junit 4 testing with spring 3.0 and Hibernate 3 in Eclipse - LazyInitializationExceptionjunit 4 在 Eclipse 中使用 spring 3.0 和 Hibernate 3 进行测试 - LazyInitializationException
【发布时间】:2010-10-08 18:44:16
【问题描述】:

我在尝试使用标题中定义的工具堆栈测试我的 DAO 方法时遇到 LazyInitializationException。我的理解是我的测试必须在休眠会话之外运行,或者在我尝试从我的 DAO 读取子对象之前它已经关闭。通过阅读文档,我了解到使用 @TransactionConfiguration 标记将允许我定义运行测试的事务管理器。

我已多次阅读文档和无数论坛帖子。仍然把我的头撞到我的键盘上......我错过了什么?感谢您的帮助!

我的单元测试类:

    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(locations = {
      "classpath:/WEB-INF/applicationContext-db.xml",
      "classpath:/WEB-INF/applicationContext-hibernate.xml",
      "classpath:/WEB-INF/applicationContext.xml" })
    @TestExecutionListeners({DependencyInjectionTestExecutionListener.class, CleanInsertTestExecutionListener.class})
    @DataSetLocation("test/java/com/yada/yada/dao/dbunit-general.xml")
    @TransactionConfiguration(transactionManager="transactionManager", defaultRollback = true)
    @Transactional
    public class RealmDAOJU4Test {

     @Autowired
     private DbUnitInitializer dbUnitInitializer;

     @Autowired
     private RealmDAO realmDAO;

     @Test
     public void testGetById() {
      Integer id = 2204;
      Realm realm = realmDAO.get(id);
      assertEquals(realm.getName().compareToIgnoreCase(
        "South Technical Realm"), 0);
      assertEquals(8, realm.getRealmRelationships().size());
     }
}

我的 applicationContext-hibernate.xml:

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
  <property name="dataSource" ref="dataSource"></property>
  <property name="useTransactionAwareDataSource" value="true" />
   ... other properties removed ...
</bean>

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

我在 applicationContext.xml 中的 dao 定义

<bean id="realmDAOTarget" class="com.yada.yada.dao.hibernate.RealmDAOImpl">
  <property name="sessionFactory" ref="sessionFactory" />
 </bean>
 <bean id="realmDAO" class="org.springframework.aop.framework.ProxyFactoryBean">
  <property name="proxyInterfaces">
   <value>com.yada.yada.dao.RealmDAO</value>
  </property>
  <property name="interceptorNames">
   <list>
    <value>hibernateInterceptor</value>
    <value>realmDAOTarget</value>
   </list>
  </property>
 </bean>

【问题讨论】:

    标签: eclipse unit-testing hibernate spring junit4


    【解决方案1】:

    好吧,对于任何在家跟随的人,这就是我想念的:

    TransactionalTestExecutionListener

    @TestExecutionListeners 列表中需要 @Transactional 批注才能发挥作用。

    【讨论】:

    • 谢谢,刚刚去谷歌搜索 SessionFactories 并找到了主题。
    • 效果很好,只花了我一个晚上的时间就到了这篇文章,谢谢!
    猜你喜欢
    • 2016-02-04
    • 2015-06-23
    • 1970-01-01
    • 2017-05-04
    • 2012-02-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多