Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>One approach that works is to create a "data initialiser" class, add it to a test Spring application context that also has your data source, and wire this application context into your tests. This relies on the fact that Spring caches the application context between test invocations.</p> <p>For example, a test superclass:</p> <pre><code>@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations={"classpath:test-application-context.xml"}) @Transactional public abstract class DataLoadingTest { @Autowired protected DatabaseInitialiser databaseInitialiser; } </code></pre> <p>With <code>test-application-context.xml</code>:</p> <pre><code>&lt;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"&gt; &lt;bean id="dataSource" .../&gt; &lt;bean class="DatabaseInitialiser"&gt; &lt;property name="dataSource" ref="dataSource"/&gt; &lt;/bean&gt; &lt;/beans&gt; </code></pre> <p>And</p> <pre><code>public class DatabaseInitialiser extends JdbcDaoSupport { @PostConstruct public void load() { // Initialise your database here: create schema, use DBUnit to load data, etc. } } </code></pre> <p>In this example:</p> <ul> <li>all tests that rely on the database extend <code>DataLoadingTest</code>;</li> <li>Spring initialises the application context upon first test invocation;</li> <li>this calls <code>DatabaseInitialiser.load()</code>, via the <code>@PostConstruct</code> annotation;</li> <li>Spring keeps the application context in a cache;</li> <li>further test invocations wire in the <code>DatabaseInitialiser</code> from the application context, which is already cached;</li> <li>tests are transactional, and roll back at the end to the initial data set.</li> </ul> <p>Likewise, <code>DatabaseInitialiser</code> can have a method annotated <code>@PostDestroy</code> to perform any rollback necessary at the end of the whole test run.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload