DAO单元测试 [英] DAO Unit testing

查看:101
本文介绍了DAO单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在研究EasyMock以及有关将其用于单元测试DAO类和外部容器测试的教程/示例。但是,我认为大多数人都在谈论测试服务层,而是模拟DAO类。我有点困惑,这真的是您如何对DAO层进行单元测试吗?

I have been looking at EasyMock and tutorials/examples around using it for Unit Testing DAO classes, for an "outside container" test. However, I think most of them talk about testing the Service Layer instead, mocking the DAO class. I am a bit confused, is it really how you Unit Test the DAO layer?

有人会说测试与DB& EJB实际上是集成测试,而不是单元测试,但是您如何知道您的SQL是否正确(假设没有ORM),而DAO则从真实(读取的本地数据库)中插入/查询正确的数据(类似于生产中的本地数据库)数据库?

Some would say that the tests interacting with DB & EJBs are actually Integration tests and not Unit tests but then how would you know if your SQL is correct (assuming no ORM) and your DAO inserts/queries the right data from your real (read, local database which is similar to that in production) database?

我读到DBUnit是针对这种情况的解决方案。但是我的问题是关于使用DBUnit之类的外部容器框架。如果DAO依赖于某些EJB,我们该如何处理事务,如果有触发器更新插入内容上的其他表怎么办?

I read that DBUnit is a solution for such a situation. But my question is about using a framework like DBUnit "outside container". What if the DAO depends on some EJBs, how do we handle the transactions, what happens if there are triggers that update other tables on your inserts?

仅对具有此类依赖性的DAO进行单元测试的最佳方法是什么?

What is the best way to Unit Test only the DAOs with such dependencies?

推荐答案

个人而言,我通过点击某种测试数据库来对DAO进行单元测试,最好是与您的应用在生产中使用的数据库类型相同(显然不是SAME数据库)。

Personally, I unit test DAOs by hitting some sort of test database, preferable the same type of database (not the SAME database, obviously) that your app uses in production.

我认为,如果这样做,则该测试更像是集成测试,因为它依赖于正在运行的数据库。这种方法的好处在于,它尽可能接近您正在运行的生产环境。它的缺点是需要测试配置,需要运行的测试数据库(在计算机本地或环境中的某个位置),并且测试可能需要更长的时间才能运行。您还需要确保在执行测试后回滚测试数据。

I think if you do that, the test is more of an integration test, because it has a dependency on a running database. This approach has the benefit in that it is as close as possible to your running production environment. It has the downsides that you need test configuration, you need a running test database (either local to your machine or somewhere in your environment) and the tests can take longer to run. You also need to be sure to rollback the test data after tests execute.

测试完DAO之后,一定要对它们进行模拟以对您的服务进行单元测试。

Once DAOs are tested, definitely mock them to unit test your services.

这篇关于DAO单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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