在我的春天结构,我已经要求的会议应保持开放在我的意见:

  <bean name="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor">
    <property name="sessionFactory" ref="sessionFactory"/>
    <property name="flushMode" value="0" />
  </bean> 

然而,这种豆obiously不考虑我的TestNG单元的测试作为一个图。;-)的所有权利,但是有一个类似的豆单元的测试,以便避免可怕的LazyInitializationException同时单元的测试?迄今为止,我一半的单元测试的死因为它.

我单元的测试通常是这样的:

@ContextConfiguration({"/applicationContext.xml", "/applicationContext-test.xml"})
public class EntityUnitTest extends AbstractTransactionalTestNGSpringContextTests {

  @BeforeClass
  protected void setUp() throws Exception {
    mockEntity = myEntityService.read(1);
  }

  /* tests */

  @Test
  public void LazyOneToManySet() {
    Set<SomeEntity> entities = mockEntity.getSomeEntitySet();
    Assert.assertTrue(entities.size() > 0); // This generates a LazyInitializationException
  }



}

我已经尝试改变setUp():

private SessionFactory sessionFactory = null;

@BeforeClass
protected void setUp() throws Exception {
  sessionFactory = (SessionFactory) this.applicationContext.getBean("sessionFactory");
  Session s = sessionFactory.openSession();
  TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s));

  mockEntity = myEntityService.read(1);
}

但我认为这是错误的方式去,我乱七八糟的事务为后来的测试。是不是有什么喜欢一个OpenSessionInTestInterceptor,是否有更好的方式这样做,或者是这个方式做到这一点,在这种情况下我有什么误会?

欢呼

Nik

有帮助吗?

解决方案

嗯..不是一个聪明的屁股在这里,但这并不是什么 setUp() 目。

基本的想法是要有你的测试以自给自足和重入这意味着你不应该依赖于数据库是具有特定的记录也不应永久性地改变该数据库在你的测试。该进程,因此,是为了:

  1. 建立任何必要的记录中 setUp()
  2. 运行实际测试
  3. 清理(如需要)在 tearDown()

(1),每个(2)和(3)所有运行中独立的交易,因此问题你得到与LazyInitializationException。移动 mockEntity = myEntityService.read(1); 从安装到你的实际测试(s)和它会去;使用的设置,如果你需要创建一些测试数据,而不直接补充,以你个人的测试。

其他提示

我使用的JUnit我的测试,所以你需要适应下面的例子来TestNG的。 Personnaly我使用基于SpringJUnit4ClassRunner在碱测试类绑定交易:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:/applicationContext-struts.xml")
@TransactionConfiguration(transactionManager = "transactionManager")
@Transactional
public abstract class BaseTests {

和在 “@Before”,我在RequestContextHolder注入MockHttpServletRequest:

@Before
public void prepareTestInstance() throws Exception {
    applicationContext.getBeanFactory().registerScope("session", new SessionScope());
    applicationContext.getBeanFactory().registerScope("request", new RequestScope());
    MockHttpServletRequest request = new MockHttpServletRequest();

    ServletRequestAttributes attributes = new ServletRequestAttributes(request);
    RequestContextHolder.setRequestAttributes(attributes);

     .......

我把信息从手册

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top