views:

42

answers:

2

I'm trying to integration test my application with Spring TestContext framework. I have done this by extending AbstractTransactionalJUnit4SpringContextTests, as usual. However, my application has three different data sources (with names like xDataSource, yDataSource, zdataSource), så when I try to run the test, the autowiring of data source in AbstractTransactionalJUnit4SpringContextTests won't work, since it looks for a Data Source with autowire-by-type, but finds three, so it does not know which one to choose.

Is there any way to get Spring TestContext Framework to use three data sources? If so; how?

A: 

You can define one of the data-sources as primary="true" in your xml, and it will be chosen.

If you need all threem then you cannot rely on autowiring - use ReflectionTestUtils to set it manually in your tests.

Bozho
That's not good enough - I need all three.
mranders
then you can't rely on autowiring. See updated
Bozho
I'm not necessarily relying on autowiring, but the thing is that `AbstractTransactionalJUnit4SpringContextTests` autowires a data source. This is for use in the simpleJdbcTemplate the class offers for doing simple queries in the test. If I setup the test using only annotations, the problem disappears. However, I want all datasources to run in the same transaction.
mranders
Well, ReflectionTestUtils should work then. Perhaps you should also obtain the dao and set it there.
Bozho
+1  A: 

OK, I figured it out. The answer to this question is twofold. Firstly, extending AbstractTransactionalJUnit4SpringContextTests won't work. This is because it needs a single data source for creating the SimpleJdbcTemplate for verifying stuff with simple JDBC queries in the test. Since I don't use this feature in this test, I could replace extends AbstractTransactionalJUnit4SpringContextTests with the collowing configuration:

@ContextConfiguration(locations = "classpath:applicationContext.xml")
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
    DependencyInjectionTestExecutionListener.class,
    DirtiesContextTestExecutionListener.class,
    TransactionalTestExecutionListener.class
})
@Transactional
public class IntegrationTest {
  ...
}

The combination of these annotations gives the same setup as extending AbstractTransactionalJUnit4SpringContextTests.

The second part was understanding that since I have three data sources, I also need all three so be referenced by the same PlatformTransactionManager. I have distributed transactions. This is impossible with a DataSourceTransactionManager, so I had to use a JtaTransactionManager.

mranders
Note that you don't need to specify `@TestExecutionListeners` - these listeners are enabled by default.
axtavt