One approach that works is to create a "data initializer" class, add it to the test context of the Spring application, which also has your data source, and associate this application context with your tests. It depends on the fact that Spring caches the application context between test calls.
For example, a test superclass:
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:test-application-context.xml"}) @Transactional public abstract class DataLoadingTest { @Autowired protected DatabaseInitialiser databaseInitialiser; }
With test-application-context.xml :
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="dataSource" .../> <bean class="DatabaseInitialiser"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
and
public class DatabaseInitialiser extends JdbcDaoSupport { @PostConstruct public void load() {
In this example:
- all database-based tests are extended by
DataLoadingTest ; - Spring initializes the application context on the first call of the call;
- this calls
DatabaseInitialiser.load() via the @PostConstruct annotation; - Spring maintains the application context in the cache;
- additionally check the call wire in the
DatabaseInitialiser from the application context, which is already cached; - tests are transactional and roll back at the end to the original dataset.
Similarly, DatabaseInitialiser can have an annotated @PostDestroy method to perform any rollback required at the end of the entire test run.
Kkkev Jan 25 2018-12-12T00: 00Z
source share