Edit: As of Spring 6.1, around October 2023, there are 2 new execution modes: BEFORE_TEST_CLASS
and AFTER_TEST_CLASS
If you're using a version before that, my original answer follows:
You can't do that out-of-the-box. The @Sql
annotation only has two modes - BEFORE_TEST_METHOD
and AFTER_TEST_METHOD
.
The listener responsible for executing these scripts, SqlScriptsTestExecutionListener
, does not implement before or after-class methods.
To work around this, I'd implement my own TestExecutionListener
, wrapping the default SqlScriptsTestExecutionListener
. You can then declare on your test to use the new listener rather than the old ones.
public class BeforeClassSqlScriptsTestExecutionListener implements TestExecutionListener
{
@Override
public void beforeTestClass(final TestContext testContext) throws Exception
{
// Note, we're deliberately calling beforeTest*Method*
new SqlScriptsTestExecutionListener().beforeTestMethod(testContext);
}
@Override
public void prepareTestInstance(final TestContext testContext) { }
@Override
public void beforeTestMethod(final TestContext testContext) { }
@Override
public void afterTestMethod(final TestContext testContext) { }
@Override
public void afterTestClass(final TestContext testContext) { }
}
Your test would then become:
@TestExecutionListeners(
listeners = { BeforeClassSqlScriptsTestExecutionListener.class },
/* Here, we're replacing more than just SqlScriptsTestExecutionListener, so manually
include any of the default above if they're still needed: */
mergeMode = TestExecutionListeners.MergeMode.REPLACE_DEFAULTS
)
@org.springframework.test.context.jdbc.Sql(
scripts = "classpath:schema-test.sql",
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
)
public class MyTest
{
@Test
public void test1() { }
@Test
public void test2() { }
}