简体   繁体   English

我应该使用mock或dbunit来测试访问数据库的方法吗?

[英]Should I use mock or dbunit to test a method which access to a database?

I've got a method which does some calls to a database using some DAO. 我有一个方法,它使用一些DAO调用数据库。

Should I use mock mechanism to avoid managing a database (and so mock all DAO methods) or should I use dbunit (or some equivalent) to test by loading and init a database in memory (like hsqldb) ? 我应该使用模拟机制来避免管理数据库(以及模拟所有DAO方法),还是应该使用dbunit(或某些等价物)通过在内存中加载和初始化数据库来测试(如hsqldb)?

Are these any pros and cons for each method (mock vs dbunit) ? 这些方法的优缺点是什么(mock vs dbunit)?

You want to test the database. 您想测试数据库。 I don't see how mock makes sense in this context. 在这种情况下,我没有看到模拟是否有意义。 Once you know the DAOs are working, then injecting mocks into services that uses them fits. 一旦你知道DAO正在工作,那么将模拟注入使用它们的服务就适合了。

In the meantime, do test your database. 在此期间,请测试您的数据库。 You can either create a temporary test database or make all your tests transactional: set up the test unit of work, execute it, validate it, roll it back. 您可以创建临时测试数据库,也可以使所有测试都是事务性的:设置测试工作单元,执行它,验证它,回滚它。

I would recommend using mock obejcts, in general Database access is not really performant and costs much time, we had a project with over 4000 unit tests, it took more than 3 hours to run the complete tests, specially when consider that the setup and tear down access the database before and after each test. 我建议使用模拟对象,一般情况下,数据库访问并不是真正的高性能并花费很多时间,我们有一个项目有超过4000个单元测试,运行完整的测试需要3个多小时,特别是考虑到设置和撕裂在每次测试之前和之后访问数据库。

regarding dbunit I used it so I can not really say if its good or not, but as said i would avoid database access in a unit test, it should be limited to the logic units only. 关于dbunit,我使用它,所以我不能说它的好坏与否,但正如我所说的,我会避免在单元测试中访问数据库,它应该仅限于逻辑单元。

It's a tough question to answer definitively; 这绝对是一个难以回答的问题; however, what I would suggest and what I have generally preferred, is to test the DAO itself against an embedded database or an external test database (as an integration test) so that you know your DAO functions properly against a read database of some sort. 但是,我建议和我通常更喜欢的是,针对嵌入式数据库或外部测试数据库(作为集成测试)测试DAO本身,以便您了解DAO对某种读取数据库的正确运行。

Then for components that use the DAO, you can mock it to decouple your tests from having to use a database explicitly. 然后,对于使用DAO的组件,您可以模拟它以将测试与必须显式使用数据库分离。

The cons for this approach are that you have to have some sort of embedded or other DB available for testing. 这种方法的缺点是你必须有某种嵌入式或其他数据库可用于测试。

You can mock your DAO unit tests; 你可以模拟你的DAO单元测试; however, you are then not entirely sure that your mocking is going to be a true representation of what the DB will provide. 但是,您并不完全确定您的模拟将成为数据库将提供什么的真实表示。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM