加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 23:56:27 所属栏目:Java 来源:网络整理
导读:我使用Flyway来管理我的 Spring MVC应用程序中的数据库状态. 我在我的servlet上下文XML文件中配置它与their docs中的推荐完全相同 bean id="flyway" class="org.flywaydb.core.Flyway" init-method="migrate" property name="dataSource" ref="..."/ .../bea
我使用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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读