使用Hibernate / Spring / JUnit安装和拆卸复杂数据库状态 [英] Setup and Tear Down of Complex Database State With Hibernate / Spring / JUnit

查看:118
本文介绍了使用Hibernate / Spring / JUnit安装和拆卸复杂数据库状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,我正在进行单元测试,在单个测试方法可以运行之前需要进行相当广泛的数据库设置。此设置需要很长时间:出于希望与手头问题无关的理由,我需要以编程方式填充数据库,而不是从SQL转储。



问题I有撕下来。我怎样才能轻松地回滚在数据库设置阶段所做的所有更改?



我目前使用Hibernate + Spring Transactional Testing支持,这样我的单个测试方法被包装在交易中。

一种解决方案是在每个测试方法中执行数据库设置,以便数据库设置自动回滚。但是,由于每种方法都需要重新准备数据库,所以测试方法将会持续运行。



还有其他想法吗?基本上,我正在寻找一种方法来运行我的数据库设置,运行我的单个测试(每个测试包裹在事务中,在执行后回滚),然后回滚最初的数据库设置。任何想法使这个工作在Hibernate / Spring / Junit时尚?是否有一个Hibernate的drop all tables等价命令?

解决方案

您是否坚持使用特定的数据库供应商?如果没有,您可以使用内存数据库,例如 HSQLDB 。当你完成测试时,你只需要抛弃状态。这仅适用于在测试套件开始时表格可能为空的情况下(即在程序设置之前)。



您仍然需要创建表格,但如果所有东西都使用Hibernate进行整齐映射,那么可以使用hbm2ddl来生成表格。您只需将以下内容添加到您的 test 会话工厂定义中:

 < session -factory> 
...
< property name =hibernate.hbm2ddl.auto> create< / property>
...
< / session-factory>

如果此解决方案似乎适用,我可以详细阐述它。


I have a class I'm unit testing that requires fairly extensive database setup before the individual test methods can run. This setup takes a long time: for reasons hopefully not relevant to the question at hand, I need to populate the DB programatically instead of from an SQL dump.

The issue I have is with the tear-down. How can I easily rollback all the changes made in the db setup phase?

I'm currently using Hibernate + Spring Transactional Testing support, such that my individual test methods are wrapped in transactions.

One solution would be to do the db setup within each test method, such that the db setup would be rolled back automatically. However, the test methods would take forever to run since each method would need to re-prep the database.

Any other ideas? Basically, I'm looking for a way to run my db setup, run my individual tests (each wrapped in a transaction which gets rolled-back after execution), and then roll-back the initial db setup. Any ideas on making this working in a Hibernate / Spring / Junit fashion? Is there a Hibernate "drop all tables" equivalent command?

解决方案

Are you stuck with a specific database vendor? If not, you could use an in-memory database, such as HSQLDB. When you are done with the tests you just throw away the state. This is only appropriate if the tables can be empty at the start of the test suite (before your programmatic setup, that is).

You still need to create tables, but if everything is neatly mapped using Hibernate you can use the hbm2ddl to generate your tables. All you have to do is add the following to your test session factory definition:

<session-factory>
    ...
    <property name="hibernate.hbm2ddl.auto">create</property>
    ...
</session-factory>

If this solution seems applicable I can elaborate on it.

这篇关于使用Hibernate / Spring / JUnit安装和拆卸复杂数据库状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆