Junit - 测试 Hibernate 服务结果
我有一个 DAO 服务,可以检索数据并将数据保存到 Hibernate。 有人可以指出我使用 JUnit 测试此类服务的方法吗?
最佳实践是什么?我应该什么时候通过测试失败的测试以及应该测试异常?
I have a DAO service which retrieves and saves data to Hibernate.
Could anybody point me to testing Methodology using JUnit for such service.
What is the best practice? When should I have passed test failed test and should I test exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您应该测试 DAO 中每条可能的路径。您肯定会使用内存数据库进行测试,例如
HSQLDB
。一种策略是在
setUp()
方法中为数据库提供一些初始数据,并在tearDown()
中清理它,以便所有测试都有一致的工作环境。通过这些设置,您基本上可以完成所有操作...例如,如果您想在 DAO 中测试
save()
方法,只需添加新元素并确保您的表现在多了一个元素。此外,获取该元素并将其与您插入的元素进行比较,它显然应该是相同的。请记住,您应该始终测试每条可能的路径。
You should test every possible path in your DAO. You would definitely use an in-memory database for your tests, such as
HSQLDB
.One strategy would be to give the database some initial data in your
setUp()
method and clean it up ontearDown()
, so all tests have a consistent working environment.With these setup you can basically do everything... For example, if you want to test a
save()
method in your DAO, just add the new element and make sure that your table now has one more element. Moreover, fetch that element and compare it to the one you've inserted, it should obviously be the same.Remember that you should always test every possible path.
我还会考虑使用 DBUnit 来确保您的数据库是一致的并且独立于测试。他们有关于如何入门的文章和教程。有相当多的 IBM DeveloperWorks 博客上的文章以及您可能想阅读的内容。
I would also look into using DBUnit to ensure that your database is consistent and test independent. They have articles on how to get started and a tutorial. There a quite a few articles on IBM's DeveloperWorks blog as well that you might want to read.
我认为使用内存数据库通常是一个好主意 - 对于单元测试。但理想的是将快速单元测试与此类数据库结合起来,并针对真实数据库进行集成测试。例如,Hysonic SQL 和大多数生产服务器之间存在细微的差异。
考虑使用模拟来测试错误处理(即模拟 Hibernate 会话对象并使其针对某些操作抛出异常)
I think using an in-memory database is often a good idea - for unit test. But the ideal is to combine fast unit tests with such a database with integration tests hitting the real database. There are subtle differences between, e.g., Hypersonic SQL and most production servers.
Consider using mocks for testing your error handling (i.e. mock the Hibernate session object and make it throw exceptions for certain operations)