对使用数据库的代码进行单元测试 [英] Unit testing on code that uses the Database
问题描述
我很想知道人们在开发使用数据库的自动化单元测试时采用什么方法
I'm interested to know what approach people are taking in developing automated unit tests that exercise the database
您是否在运行测试套件之前安装了 QA 数据库(已知起点).
Do you Install a QA database (known-starting point) before the test suite is run.
或
您是否构建了数据库存根以在发生数据库调用时充当替身?
Do you build database stub that stand-in whenever a database call occurs?
相关问题,但不是重复的,虽然对手头的事情很重要:如何对持久性进行单元测试?
Related question, but not a duplicate, though quite important for the matter at hand: How do I unit-test persistence?
推荐答案
位于其中的数据库存根"通常被称为假存储库"或模拟存储库".他们是个好主意.您可以手工编写它们(对于简单的情况来说并不难)或使用 Rhino Mocks 之类的框架来生成它们.您没有提及您使用的语言.Rhino 模拟适用于 .Net.
The "database stub" that stands in is usually referred to as a "fake repository" or "mock repository". They are a good idea. You can code them by hand (not hard for simple cases) or use a framework like Rhino Mocks to generate them. You don't mention what language you are working in. Rhino mocks is for .Net .
如果您使用模拟存储库,那么您可以针对处理数据的代码运行测试,而无需实际使用数据库来存储数据.这使得测试运行得非常快,这是一件好事.
If you use mock repositories then you can run tests against code that works with data, without actually using a database for the data. This makes the tests run very fast, which is a good thing.
当然,您仍然需要在某个阶段测试真实的存储库,这更多的是一个问题.这些测试会运行得更慢,因为它们使用的是真实的数据库.由于速度和依赖性问题,有些人会将其归类为集成测试"而不是单元测试.
Of course, you still have to test the real repository at some stage, and this is more of an issue. These tests will run slower, because they use a real database. Some would classify then as "integration tests" not unit tests because of the speed and dependency issues.
我不介意你怎么称呼它们,但将这些测试分开是个好主意.
I don't mind what you call them so much, but it's a good idea to keep these tests separate.
这里数据一致性的一个好主意是在测试之前开始一个数据库事务,然后回滚它.这样数据库状态就会恢复到测试前的状态.
A good idea here for data consistency is to begin a db transaction before your test, and roll it back afterwards. That way the database state is reverted to what it was before the test.
这篇关于对使用数据库的代码进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!