Spring @Transactional 在 JUnit 测试中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10718916/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Spring @Transactional does not work in JUnit test?
提问by Nilesh
I am using Spring 3.2, Hibernate and JUnit 4.
我使用的是 Spring 3.2、Hibernate 和 JUnit 4。
My Dao class is as follows:
我的Dao类如下:
@Transactional public class SomeDaoImpl implements SomeDao {
@Transactional public class SomeDaoImpl implements SomeDao {
The update operations on this work if executed directly from web application. However, I am seeing that junit integration tests that exercise the update methods do not actually persist the changes. Is something rolling the transactions back when junit methods are executed?
如果直接从 Web 应用程序执行此工作的更新操作。但是,我看到使用更新方法的 junit 集成测试实际上并没有保留更改。执行junit方法时是否会回滚事务?
回答by nobeh
By reference, transactions are notpersisted in test contexts in Spring. As mentioned, although unusual, if you still need to do so you can use @TransactionConfigurationand @Rollbackto change the default behavior.
通过引用,事务不会在 Spring 的测试上下文中持久化。如前所述,虽然不寻常,但如果您仍然需要这样做,您可以使用@TransactionConfiguration并@Rollback更改默认行为。
回答by duffymo
DAOs should not be transactional. How can a DAO know if it should participate in a larger transaction?
DAO 不应该是事务性的。DAO 如何知道它是否应该参与更大的交易?
Services ought to own transactions in the typical Spring layered architecture.
在典型的 Spring 分层架构中,服务应该拥有事务。
It's typical to run your unit tests for databases in such a way that they do roll back. You don't want your tests to alter the database, unless you've set up a test database that you can drop and recreate at will.
通常以回滚的方式运行数据库单元测试。你不希望你的测试改变数据库,除非你已经建立了一个可以随意删除和重新创建的测试数据库。
The question ought to be: How do your tests, as written, commit the transaction? If you never commit, you'll never see the records.
问题应该是:您编写的测试如何提交事务?如果你从不提交,你就永远不会看到记录。
回答by stevedbrown
From the "Testing" section of the docs, you can use the
从文档的“测试”部分,您可以使用
@Rollback(false)
annotation if you don't want SpringJUnit4ClassRunner to roll back your transactions.
如果您不希望 SpringJUnit4ClassRunner 回滚您的事务,请使用注释。

