任何存储库/DAO 实现中值得测试的部分是查询。为确保这些查询正确,您必须在实际数据库中运行它。
鉴于上述事实,对 DAO/Respositories 进行单元测试是否有意义?如果是,最佳做法是什么?
任何存储库/DAO 实现中值得测试的部分是查询。为确保这些查询正确,您必须在实际数据库中运行它。
鉴于上述事实,对 DAO/Respositories 进行单元测试是否有意义?如果是,最佳做法是什么?
我非常虔诚地对我的存储库进行单元测试。实际上,它们可能是我最重要的单元测试。
如果您使用诸如 NHibernate 之类的 ORM,这实际上会非常轻松。
我使用包含 setup 和 teardown 的基本夹具来创建内存中的 sqlite db,然后在每次测试结束时将其销毁。这出奇的快。然后对于每个存储库,我都有一个为我的测试注入测试数据的设置。这是非常独立的,可以捕获我的存储库查询中的所有逻辑问题。
它唯一没有捕捉到的是数据库提供者特定的情况,但是当使用像 NHibernate 这样的东西时,这些通常是例外。
对于测试数据库特定查询的特殊情况,您可能需要一套使用不同设置和拆卸方法的测试。不幸的是,这些测试会比您的其他单元测试更慢并且可能更脆弱(这就是为什么它们应该组合在一起)。
If "express" editions of the database software you are testing are available I still recommend that the database be set up locally on the fly so that you always ensure that the database your tests run against has the schema they expect. I would change one part of the setup and teardowns of this though. I would only setup and teardown the database at the beginning and end of the entire run of tests. Then every tests setup and teardown should start a transaction, then roll it back at the end. This is a quick way of keeping things compartmentalized between the tests. The last thing you want is for data from one test to affect another test.
Yes doing unit tests for DAO layer is a must. In java there are frameworks like dbUnit helps you in doing that. Keeping a separate schema/instance in the database with some bootstrap data will help you do right unit testing and you can cover most of the scenarios.