java – Spring MVC – 使用Flyway在测试之间清理数据库

我使用Flyway来管理我的 Spring MVC应用程序中的数据库状态.

我在我的servlet上下文XML文件中配置它与their docs中的推荐完全相同

<bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate">
    <property name="dataSource" ref="..."/>
    ...
</bean>

<!-- The rest of the application (incl. Hibernate) -->
<!-- Must be run after Flyway to ensure the database is compatible with the code -->
<bean id="sessionFactory" class="..." depends-on="flyway">
    ...
</bean>

我想在JUnit测试中做两件事 –

>一旦在所有测试之前,删除并重新创建数据库并让它重新迁移.这为每个测试套件创建了一个干净的数据库.
>在每次测试之前,清理所有数据库表.在其他框架(例如RSpec / Rails)中,我通过事务运行DB语句来完成此操作,因此它们在测试结束时回滚.不确定Spring MVC世界中的最佳实践是什么.

我不知道从哪里开始实施上述内容,所以任何指导都表示赞赏.

谢谢!

解决方法

首先,您可以在每次测试之前清理数据库,如下所示:
@Autowired
 Flyway flyway;

@Before
puublic void init(){
   flyway.clean();
   flyway.migrate();
}

其次,您可以使用JdbcTestUtils删除表中的所有行.
在这里找到doc:JDBC测试支持https://docs.spring.io/spring/docs/current/spring-framework-reference/html/integration-testing.html

您还可以使用@Rollback和@Commit以事务方式运行测试方法

@Rollback indicates whether the transaction for a transactional test method should be rolled back after the test method has completed. If true,the transaction is rolled back; otherwise,the transaction is committed (see also @Commit). Rollback semantics for integration tests in the Spring TestContext Framework default to true even if @Rollback is not explicitly declared.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...