【发布时间】:2020-09-29 08:08:15
【问题描述】:
在 Spring data JPA 中有一个 @Sql 注释,对于设置持久层的集成测试非常方便。它可以在每次测试之前推出测试数据并在之后执行清理。
但是,我在 spring-data-r2dbc 模块中找不到它。 spring-data-r2dbc有没有类似轻松处理这个任务的东西?
【问题讨论】:
标签: spring-data project-reactor spring-data-r2dbc
在 Spring data JPA 中有一个 @Sql 注释,对于设置持久层的集成测试非常方便。它可以在每次测试之前推出测试数据并在之后执行清理。
但是,我在 spring-data-r2dbc 模块中找不到它。 spring-data-r2dbc有没有类似轻松处理这个任务的东西?
【问题讨论】:
标签: spring-data project-reactor spring-data-r2dbc
目前我还没有找到比将 org.springframework.data.r2dbc.connectionfactory.init.ScriptUtils#executeSqlScript(io.r2dbc.spi.Connection, org.springframework.core.io.Resource) 与 JUnit @BeforeEach 和 @AfterEach 测试回调一起使用更好的方法:
@Autowired
private ConnectionFactory connectionFactory;
private void executeScriptBlocking(final Resource sqlScript) {
Mono.from(connectionFactory.create())
.flatMap(connection -> ScriptUtils.executeSqlScript(connection, sqlScript))
.block();
@BeforeEach
private void rollOutTestData(@Value("classpath:/db/insert_test_data.sql") Resource script) {
executeScriptBlocking(script);
}
@AfterEach
private void cleanUpTestData(@Value("classpath:/db/delete_test_data.sql") Resource script) {
executeScriptBlocking(script);
}
注意:这里我使用 JUnit5 和 jupiter API
【讨论】:
如果您愿意,您可以在集成测试中以简单的方式使用@Sql,这样您就可以使用您熟悉的东西。即使您使用的是 r2dbc,您也可以在 pom.xml/gradle 文件中添加此依赖项:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
</dependency>
所以你有两个驱动程序(阻塞和非阻塞版本)。这种依赖关系在其他情况下可能很有用(例如,如果您使用 Flyway - 它还不支持反应式驱动程序)。然后,您可以创建一个可以在集成测试中使用的 @Configuration 类。如果你在集成测试中使用 postgresql,你会得到类似的东西:
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import javax.sql.DataSource;
@Configuration
public class TestConfig {
/**
* Necessary to run sql scripts with @Sql
*/
@Bean
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName("org.postgresql.Driver");
dataSource.setUrl("jdbc:postgresql://localhost:5432/postgres");
dataSource.setUsername("postgres");
dataSource.setPassword("1234");
return dataSource;
}
}
要测试您的数据库,您的测试将从以下内容开始:
@DataR2dbcTest
@ActiveProfiles("test")
@Sql(value = "classpath:sql/MovieInfoRepositoryITest.sql")
@Import({TestConfig.class})
class MovieInfoRepositoryITest {
...
}
不要害怕在对反应式应用程序不“痛苦”的地方使用 JDBC 驱动器,例如在测试期间执行 sql 脚本。
【讨论】: