微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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.

原文地址:https://www.jb51.cc/java/127194.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐