gpt4 book ai didi

java - Spring的测试注解@Sql如何表现得像@BeforeClass?

转载 作者:行者123 更新时间:2023-12-03 04:36:44 25 4
gpt4 key购买 nike

如何告诉 @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
}
}

最佳答案

对于 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)
// 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 :

The configuration options provided by @Sql and @SqlConfig areequivalent to those supported by ScriptUtils andResourceDatabasePopulator but are a superset of those provided by the <jdbc:initialize-database/> XML namespace element.

奖金

您可以将此方法与其他方法混合使用 @Sql声明。

关于java - Spring的测试注解@Sql如何表现得像@BeforeClass?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47775560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com