使用 spring 对 hibernate daos 进行单元测试
我喜欢为我的 hibernate dao 实现编写 JUnit,并寻求有关编写这些单元测试用例的建议方法的意见。我可以想到两种策略。
使用 EasyMock 等库模拟 hibernate 模板,并针对这些模拟对象测试 DAO 实现。 (不太令人满意,因为我将针对模拟层进行测试,而不是真正针对测试数据)
通过在运行单元测试之前编写一些测试数据来针对真实的测试数据库(内存中/外部)进行测试。
哪种方法是确保我们的 DAO 得到正确测试的好方法。请指出有关使用第二种方法配置测试的任何示例。我试着环顾四周,但没有找到合适的。
谢谢, 湿婆。
I like to write JUnits for my hibernate dao implementations and seek opinion on the suggested approach for writing these unit testcases. I can think of two strategies.
Mocking hibernate template using a library like EasyMock and testing just the DAO implementation against these mock objects. (Not really satisfying as I would be testing against a mock layer and not really against test data)
Testing against a real test database (an in-memory/external) by writing some test data before running my unit test.
Which approach is a good way of ensuring our DAOs are properly tested. Please point me to any examples on configuring tests using the second approach. I tried looking around but haven't found the right ones.
Thanks,
Siva.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我会遵循第二种方式,使用 HSQLDB 作为数据库引擎。我认为调用 DAO 背后的实际实现对于捕获映射错误具有积极的作用。
如果您的 DAO 有更多与处理 hibernate 无关的逻辑(想象一下,如果您的 DAO 加载一些对象,然后对它们执行一些操作以返回不同的对象),我将创建一个不同的测试类来测试具有额外逻辑的方法,并模拟返回数据的方法。这允许您以更简单的方式设置数据,而不是启动数据库并立即加载这些对象。
I would follow the second way, using HSQLDB as the DB engine. I think that invoking the real implementation behind a DAO has the positive effect of catching mapping errors.
If your DAOs have more logic that it's not related to deal with hibernate (imagine if you DAO loads some objects and then performs some operations on them to return a different object), I would create a different test class to test the methods with extra logic, and mock the methods that return the data. This allows you to set up the data in an easier way rather than priming the DB and immediately loading those objects.
针对真实数据库进行测试。 Hibernate 的大部分复杂性都在于映射,如果您模拟 SessionFactory(或封装它的内容),您将完全错过对其进行测试。使用 Spring 测试框架,为了大大简化您的测试,对于本地“单元”测试,请针对内存数据库进行测试。 H2 使用简单且速度非常快(比 HSQLDB 或 Derby 更好)。例如:
Test against a real database. Most of the complexity of Hibernate is in the mapping, and if you mock the SessionFactory (or what encapsulates it), you miss testing that entirely. Use the Spring Test Framework, to greatly ease your testing, and for local, "unit" tests, test against an in-memory database. H2 is simple to use and very fast (better than HSQLDB or Derby). E.g.: