我有一个带有 junit4 测试套件的 Spring 3.1 MVC + Hibernate 3.6 项目。我的问题是我的测试用例中没有事务开始,即使我添加了一个@Transactional。
我的测试用例调用了一个控制器和一个 dao。在控制器中,无论如何都会启动事务,因此它不会抱怨。在 dao 中,我添加了一个@Transactional(propagation = Propagation.MANDATORY)以确保它将接受测试的事务。目前它引发了一个IllegalTransactionStateException,我猜这意味着没有当前事务。
我试图以编程方式创建一个事务并且它确实有效,这意味着获取 dao 服务的 AOP 代理不是问题的原因。但是我想用@Transactional注释创建一个事务。
这是我的道:
// ...imports...
@Repository("taskDao")
@Transactional(propagation = Propagation.MANDATORY)
public class TaskHome implements TaskDao {
private static final Log log = LogFactory.getLog(TaskHome.class);
private SessionFactory sessionFactory;
@Autowired
public TaskHome(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
public Task findById(int id) {
log.debug("getting Task instance with id: " + id);
try {
Task instance = (Task) this.sessionFactory.getCurrentSession().get(
Task.class, id); // exception raised here!
if (instance == null) {
log.debug("get successful, no instance found");
} else {
log.debug("get successful, instance found");
}
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
...
}
这是我的测试用例:
// ...imports...
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration({ "/test-config.xml", "/applicationContext.xml" })
@TransactionConfiguration(defaultRollback = true)
@Transactional
public class TestTaskController {
private static ClassPathXmlApplicationContext context;
private static TaskDao taskDao;
@BeforeClass
public static void initHibernate() throws Exception {
context = new ClassPathXmlApplicationContext("applicationContext.xml");
taskDao = context.getBean("taskDao", TaskDao.class);
}
@Test
public void testOnSubmit() {
// expects an existing default transaction here
Task task = taskDao.findById(1); // fails already here
// ... calls the controller and does some tests.
}
}
我搜索了 Spring 的所有文档并以我能想象的任何方式搜索它,但我不明白为什么交易没有开始。非常欢迎任何帮助。