继承ADODB_Active_Record的phpUnit和模型,存根ADODB_mysql
我到处寻找,令人惊讶的是,找不到答案。
当尝试使用 phpUnit 对我的模型进行单元测试时,如何存根数据库?
我正在使用 PHP 框架 CMS,它有许多继承自 ADODB_Active_Record 的类(“Model”)的类。模型的构造函数获取一个数据库对象(来自 ADOConnection)并将其传递给 Active_Record 的构造函数。
这可能不是最佳实践,但为了尽可能少地更改代码,我正在考虑调整grabDBObject()以在测试时返回存根对象。该存根被传递给 ADODB_Active_Record,理论上,我可以测试我的模型。
但是,我不知道如何创建存根。 ADODB_Connection 并不简单。这不是替换 Execute() 的问题。还有许多其他函数,例如 qstr(),看来我必须担心并根据需要重写。
令人惊讶的是我找不到任何关于人们这样做的讨论。这一定是一个常见问题。我是不是走错了方向?我知道我可以使用 dbUnit 之类的东西来实际执行数据库查询,而不是存根 ADODB_connection,但我也知道我应该尽可能多地存根,并且依赖数据库来进行模型方法的单元测试是不好的。
所以, 1. 我应该对数据库连接进行存根以进行单元测试吗? 2.如何?
I've searched high and low and, astonishingly, cannot find an answer.
When trying to unit test my models with phpUnit how can I stub the database?
I'm using a PHP framework CMS which has a number of classes which inherit from a class ("Model") which inherits from ADODB_Active_Record. Model's constructor grabs a db object (from ADOConnection) and passes it to Active_Record's constructor.
It might not be Best Practice, but in order to change the code as little as possible, I'm thinking of tweaking grabDBObject() to return a stub object when in testing. That stub gets passed to ADODB_Active_Record, and, in theory, I can test my models.
However, I can't figure out how to create the stub. ADODB_Connection isn't simple. It's not going to be a matter of replacing Execute(). There are a bunch of other functions, like qstr(), that it appears I'll have to worry about and rewrite as necessary.
What's surprising is I can't find any discussions of people doing this. This has got to be a common problem. Am I going in the wrong direction? I understand that I can use something like dbUnit to actually do db queries rather than stubbing ADODB_connection, but I also understand that I should stub as much as possible, and that it's bad to rely on a db for unit tests of a model's methods.
So,
1. Should I be stubbing the db connection for unit testing?
2. How?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您是否尝试过 phpunit 的 getMock() 方法?
它允许您提供一个假对象进行测试,而无需触及您的生产代码。
但在这种情况下,你必须自己构建预期的结果。
该文档在这里:
http://www.phpunit.de/manual/ 3.0/en/mock-objects.html
Have you tried the getMock() method of phpunit ?
It allows you to provide a fake object for testing, without touching your production code.
But in that case, you have to build the expected result by yourself.
The doc is here :
http://www.phpunit.de/manual/3.0/en/mock-objects.html