This code throws an IllegalStateException
(Spring 5.0.1) because of the getTestMethod()
method in DefaultTestContext.java
:
public final Method getTestMethod() {
Method testMethod = this.testMethod;
Assert.state(testMethod != null, "No test method");
return testMethod;
}
When calling the beforeTestClass
method through your proposed implementation, the textContext
does not contain a valid testMethod
(which is normal at this stage):
public class BeforeClassSqlScriptsTestExecutionListener implements TestExecutionListener {
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
new SqlScriptsTestExecutionListener().beforeTestMethod(testContext);
}
}
When the code responsible of running SQL scripts (in the SqlScriptsTestExecutionListener
) is executed, a valid testMethod
is required:
Set<Sql> sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(
testContext.getTestMethod(), Sql.class, SqlGroup.class);
I ended up using this workaround:
@Before
public void setUp() {
// Manually initialize DB as @Sql annotation doesn't support class-level execution phase (actually executed before every test method)
// See https://jira.spring.io/browse/SPR-14357
if (!dbInitialized) {
final ResourceDatabasePopulator resourceDatabasePopulator = new ResourceDatabasePopulator();
resourceDatabasePopulator.addScript(new ClassPathResource("/sql/[...].sql"));
resourceDatabasePopulator.execute(dataSource);
dbInitialized = true;
}
[...]
}