我怎么能告诉@Sql
注释只为类运行一次,而不是每个@Test
方法?
喜欢和@BeforeClass
一样的行为?
@org.springframework.test.context.jdbc.Sql(
scripts = "classpath:schema-test.sql",
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
)
public class TestClass {
@Test
public void test1() {
//runs the @Sql script
}
@Test
public void test2() {
//runs the @Sql script again
}
}
你无法做到开箱即用。 @Sql
annotation只有two modes - BEFORE_TEST_METHOD
和AFTER_TEST_METHOD
。
负责执行这些脚本的监听器SqlScriptsTestExecutionListener
没有实现before或class之后的方法。
为了解决这个问题,我将实现自己的TestExecutionListener
,包装默认的SqlScriptsTestExecutionListener
。然后,您可以在测试中声明使用新侦听器而不是旧侦听器。
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) { }
}
您的测试将变为:
@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() { }
}
由于IllegalStateException
中的getTestMethod()
方法,此代码抛出DefaultTestContext.java
(Spring 5.0.1):
public final Method getTestMethod() {
Method testMethod = this.testMethod;
Assert.state(testMethod != null, "No test method");
return testMethod;
}
通过您提议的实现调用beforeTestClass
方法时,textContext
不包含有效的testMethod
(在此阶段是正常的):
public class BeforeClassSqlScriptsTestExecutionListener implements TestExecutionListener {
@Override
public void beforeTestClass(TestContext testContext) throws Exception {
new SqlScriptsTestExecutionListener().beforeTestMethod(testContext);
}
}
当执行负责运行SQL脚本的代码(在SqlScriptsTestExecutionListener
中)时,需要一个有效的testMethod
:
Set<Sql> sqlAnnotations = AnnotatedElementUtils.getMergedRepeatableAnnotations(
testContext.getTestMethod(), Sql.class, SqlGroup.class);
我最终使用了这个解决方法:
@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;
}
[...]
}
对于JUnit 5,直接清洁解决方案:
@MyInMemoryDbConfig
//@Sql(value = {"/appconfig.sql", "/album.sql"}) -> code below is equivalent but at class level
class SomeServiceTest {
@BeforeAll
void setup(@Autowired DataSource dataSource) {
try (Connection conn = dataSource.getConnection()) {
// you'll have to make sure conn.autoCommit = true (default for e.g. H2, in memory)
// e.g. url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;MODE=MySQL
ScriptUtils.executeSqlScript(conn, new ClassPathResource("appconfig.sql"));
ScriptUtils.executeSqlScript(conn, new ClassPathResource("album.sql"));
}
}
// your @Test methods follow ...
但是当您的数据库连接未使用autoCommit = true
配置时,您必须将所有内容包装在事务中:
@RootInMemoryDbConfig
@Slf4j
class SomeServiceTest {
@BeforeAll
void setup(@Autowired DataSource dataSource,
@Autowired PlatformTransactionManager transactionManager) {
new TransactionTemplate(transactionManager).execute((ts) -> {
try (Connection conn = dataSource.getConnection()) {
ScriptUtils.executeSqlScript(conn, new ClassPathResource("appconfig.sql"));
ScriptUtils.executeSqlScript(conn, new ClassPathResource("album.sql"));
// should work without manually commit but didn't for me (because of using AUTOCOMMIT=OFF)
// I use url=jdbc:h2:mem:myDb;DB_CLOSE_DELAY=-1;MODE=MySQL;AUTOCOMMIT=OFF
// same will happen with DataSourceInitializer & DatabasePopulator (at least with this setup)
conn.commit();
} catch (SQLException e) {
SomeServiceTest.log.error(e.getMessage(), e);
}
return null;
});
}
// your @Test methods follow ...
为何清洁解决方案
因为根据Script Configuration with @SqlConfig:
@Sql和@SqlConfig提供的配置选项等同于ScriptUtils和ResourceDatabasePopulator支持的配置选项,但它们是XML命名空间元素提供的超集。
奖金
您可以将此方法与其他@Sql声明混合使用。