How to populate test data programmatically for integration tests in Spring?
<p>I am looking for the recommended approach for populating test data programmatically in integration tests using spring / spring boot. I am using HSQLDB (inmemory).</p>

<p>There is the possibility to execute SQL scripts in spring for integration tests like this:</p>

<pre class="lang-java prettyprint-override"><code>@Test
@Sql({"/test-schema.sql", "/test-user-data.sql"})
public void userTest {
    // execute code that relies on the test schema and test data
}
</code></pre>

<p>Instead of writing SQL scripts I would like to insert data for <strong>multiple</strong> test methods in one integration test programmatically like this:</p>

<pre class="lang-java prettyprint-override"><code>@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(classes = BookstoreApp.class)
@IntegrationTest
public class BookRepositoryTest {
    @Autowired
    private BookRepository bookRepository;

    @Before // not working
    public void setUp() throws Exception {
        bookRepository.save(new Book("Donald Duck 1", "Walt Disney", "0-14-020652-3"));
        bookRepository.save(new Book("Donald Duck 2", "Walt Disney", "0-14-020652-4"));
        bookRepository.save(new Book("Micky Mouse", "Walt Disney", "0-14-020652-5"));
    }

    @Test
    public void findByTitle() {
        List&lt;Book&gt; books = bookRepository.findByTitle("Duck");
        Assert.assertEquals(2, books.size());
    }

    @Test
    public void getByIsbn() {
        Book book = bookRepository.getByIsbn("0-14-020652-4");
        Assert.assertEquals("0-14-020652-4", book.getIsbn());
        Assert.assertEquals("Donald Duck 2", book.getTitle());
    }

}
</code></pre>

<p>Each Test of this example runs just fine when being executed separately. But the second one (getByIsbn) will fail, when running them together. So obviously <code>@Before</code> is the wrong annotation to use here, since the books will be inserted twice. </p>

<p>How can I enforce the database setup being executed only once?</p>