1

我有一个工作的基于 Spring/Hibernate 的 Web 应用程序。现在我需要使用 Spring JUnit 4 为其编写集成测试。这是我的测试代码:

@RunWith(SpringJUnit4ClassRunner.class)
@TransactionConfiguration(transactionManager = "hibernateTransactionManager", defaultRollback = true)
@ContextConfiguration(locations = {"classpath:applicationContext-xxx.xml", "classpath:applicationContext-xxx.xml", "classpath:applicationContext-xxx.xml", "classpath:applicationContext-xxx.xml", "classpath:applicationContext-xxx.xml", "classpath:applicationContext-xxx.xml", "classpath:applicationContext.xml"})

public class TestXXX extends AbstractTransactionalJUnit4SpringContextTests {

@Test
public void testXXXExecute(){...}
}

通过测试环境的这种设置,我可以访问所有 bean 并使用 sessionFactory bean 从数据库中获取数据。

问题发生在一项测试中,使用 TransactionSynchronizationManager 调用生产代码来实现两阶段提交。代码如下所示:

TransactionSynchronizationManager.bindResource(sessionFactoryA, new SessionHolder(sessionA));
TransactionSynchronizationManager.bindResource(sessionFactoryB, new SessionHolder(sessionB));

该代码在运行完整 Spring 框架的开发和生产环境中运行良好。在 JUnit 运行期间,异常是:

[junit] java.lang.IllegalStateException: Already value [org.springframework.orm.hibernate3.SessionHolder@6311e359] for key [org.hibernate.impl.SessionFactoryImpl@56d47236] bound to thread [main]

我无法在测试类中使用 2 行 @TransactionConfiguration 来定义对应于两个数据源和两个 sessionFactory 对象的两个事务管理器。我想知道 AbstractTransactionalJUnit4SpringContextTests 是不是不能复制真正的 Spring Framework 的事务环境。

4

1 回答 1

0

Without seeing more of your code, it is difficult to tell exactly what is wrong. In instances where I've seen this error in the past, it was because files named in the @ContextConfiguration included each other. For example, you might have file

applicationContext-bean-cfg.xml

that includes

applicationContext-hibernate-cfg.xml, but then have

@ContextConfiguration(locations = {"classpath:/applicationContext-bean-cfg.xml", "classpath:/applicationContext-hibernate-cfg.xml"}).

The other thing to check is that one of the files doesn't already have a transaction manager defined.

于 2013-10-22T21:17:36.967 回答