1

嗨,我有一个单元测试应该测试一个 cronjob

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "file:WebContent/WEB-INF/applicationContext.xml" })
@TransactionConfiguration(transactionManager = "hibernateTransactionManager")
@Transactional
public class cronTest {}

但由于事务的原因,cronjob 看不到测试的数据。但是当我删除@Transactional Hibernate 时说:

org.hibernate.HibernateException: No Session found for current thread

当我自己承诺时

sessionFactory.getCurrentSession().getTransaction().commit();
sessionFactory.getCurrentSession().beginTransaction();

测试最终失败

org.springframework.transaction.TransactionSystemException: Could not commit Hibernate transaction; nested exception is org.hibernate.TransactionException: Transaction not successfully started

如何在没有事务的情况下进行单元测试?

测试做了这样的事情:

    userDao.clear();
    loadeduser = userService.getUserById(createUser.getUserID());
    assertTrue(loadeduser.getAuthoritiesEntities().contains(adminRole));
    assertTrue(loadeduser.getAuthoritiesEntities().contains(userRole));

    // Wait for auto unsign
    TestUtils.sleep(10000);

    userDao.clear();
    loadeduser = userService.getUserById(createUser.getUserID());
    assertFalse(loadeduser.getAuthoritiesEntities().contains(adminRole));
    assertTrue(loadeduser.getAuthoritiesEntities().contains(userRole));

它检查过期角色的自动取消签名是否有效,石英作业每 5 秒运行一次

4

1 回答 1

1

通常,我建议对可以在单个事务中测试的代码使用单元测试,并使用集成测试(启动整个系统并执行您想要测试的序列)来测试多事务行为。

但是要回答这个问题:解决此问题的一种方法是像您所做的那样从测试方法中删除 @Transaction ,而不是直接使测试方法控制事务,而是允许您正在测试的方法开始/提交自己的交易(他们通常会这样做,对吧?)

例如,我们可能有通过正常 DAO 工作流运行的测试,并且每个 DAO 方法都标记为@Transactional。每个方法都控制自己的事务提交,因此我们可以在单个测试方法中测试多事务行为。该测试可能如下所示:

// no @Transactional here, dao methods are @Transactional
public void testMultiTransactionUpdate() {
    Entity t = dao.getEntity(id);
    t.setProperty("somethingnew");
    dao.update(t);
    Entity t2 = dao.getEntity(id);
    Assert.assertEquals(t1.getProperty(), t2.getProperty());
}

One thing to be careful of is that if you are committing against an in-memory database (like HSQLDB), your changes made in one test will not be automatically rolled back and will normally be visible to subsequent tests. You will have to manually undo all of your changes at the end of the test, or ensure that your test data does not interfere with other tests which is not so easy. That's why I would use this technique sparingly.

于 2012-11-21T16:27:22.757 回答