How to configure mutliple transaction managers with Spring + DBUnit + JUnit

眉间皱痕 提交于 2019-12-03 15:33:15

A possible workaround would be to introduce a helper bean annotated as @Transactional("transactionManagerTarget") and leave your test annotated as @Transactional("transactionManager"), configuring both with defaultRollback = true. Your test would then have to call the helper bean, which in turn would call your service bean under test. This should cause the transaction around your service to roll back, then the transaction around DBUnit.

It's a bit messy, though.

Other possible approaches:

  • Using an in-memory database such as H2 instead of your production database- you could configure this to drop all of its data when required.
  • Allow DBUnit to commit, and have a compensating transaction in your tear-down method to clear the data out.

Use the <qualifier> element inside your transaction manager definition.

<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSourceA" />
    <qualifier value="transactionManager" />
</bean>

<bean id="transactionManagerTarget" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
    <property name="dataSource" ref="dataSourceB" />
    <qualifier value="transactionManagerTarget" />
</bean>

Then you can reference which one you want to use directly in the @Transactional annotation, i.e.

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:resources/spring-context.xml",
                                "classpath:resources/spring-db.xml"})  
@Transactional("transactionManagerTarget")
@TransactionConfiguration(defaultRollback = true) 
public class MyIntegrationTest {
...

I have used XA transactions and rollbacks in JUnit tests using the open source TM Atomikos. One nice feature is that Atomikos allows using non-XA enabled data sources to participate in XA transactions. Check this link out for an example: http://www.atomikos.com/Documentation/NonXaDataSource

On the other hand, if XA is a decent solution for your JUnit issues is another story. Do your tests focus a lot on the database implementation (Sybase) or is it more about Java logic? I usually setup embedded DBs like Apache Derby or HQSQL for JUnit tests. Then I do not have to care much about clean ups, since GC will handle that :)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!