4

任何存储库/DAO 实现中值得测试的部分是查询。为确保这些查询正确,您必须在实际数据库中运行它。

鉴于上述事实,对 DAO/Respositories 进行单元测试是否有意义?如果是,最佳做法是什么?

4

3 回答 3

2

是 - 使用内存数据库(例如HSQLDBL )

我的这篇博文讨论了一个类似的话题。

更新:关于您的评论 - 在我链接的帖子中,ORM 用于确保数据库不一致不是问题。首先使用原始 SQL 并不是一个好主意(如果使用 OOP)。然后,您总是可以尝试尽可能使用 ANSI SQL(而不是测试不一致)。

另一种选择可能是专用一个测试数据库服务器+一个持续集成引擎,并仅在引擎内运行测试(这样来自多台机器的多个测试执行不会相互混淆)

于 2010-02-14T13:51:58.217 回答
2

我非常虔诚地对我的存储库进行单元测试。实际上,它们可能是我最重要的单元测试。

如果您使用诸如 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.

于 2010-02-14T13:56:33.027 回答
0

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.

于 2010-02-14T14:13:28.207 回答