如何在 Zend_Test_PHPUnit_ControllerTestCase 中模拟/存根对数据库的调用?
我正在编写我的第一个控制器测试。在内部,控制器必须调用(或扩展)尝试连接到数据库的文件。但是,我不希望它实际连接到数据库,因为这并不完全是我现在正在测试的(...或者我应该吗?)。无论如何,我如何模拟/存根(不确定正确的术语是什么)对数据库的调用?或者,我怎样才能至少拦截任何呼叫,以便我知道它们都发生在哪里?
I am writing my first controller test. Internally the controller must call (or extend) a file that tries to connect to the database. However, I don't want it to actually connect to a database, since that's not exactly what I'm testing right now (...or should I?). Anyway, how can I mock/stub (not sure what the correct terminology is) a call to the database? Or, how can I at least intercept any calls so I know where they are all happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般答案:是的“模拟”是这里的正确术语。您想要创建一个“假”对象,它接受已知的输入并产生已知的输出。
首先:我没有测试 Zend Framework 控制器的经验。从SO问题来看,似乎相当复杂。因此,如果没有一些示例代码,我无法生成一个工作/某种工作示例。
首先:我不确定您是否想实际连接到数据库。单元测试的“纯粹”形式告诉您针对假数据库(sqlite,在内存中)进行工作,而我目前希望确保我的查询针对真实的数据库实例进行工作,因此我再次测试我的数据库访问对象与真实的数据库。这让我想到了下一点。
您的控制器不应该与数据库通信。即使(所有/许多)模型直接与数据库对话也不是很多人认为正确的 MVC,但将 SQL 放入控制器中的 php 相当于将 html 放入应用程序逻辑 PHP 代码中,回到 php 4 天。
作为一个非常笼统的答案:
查看获取 $objectToMockOutInQuestion 的代码。当它来自构造函数参数的方法时,您已经赢了,您可以将其传入。当您的代码从容器中提取它时,请先查看是否可以将其放入该容器中。如果它是一个普通的旧
new
运算符,您可能需要更改代码。希望能有所帮助,即使只是文字
General answer: Yes "mocking" is the right term here. You want to create a 'fake' object that takes known inputs and produces known outputs.
First of all: I don't have experience with testing Zend Framework Controllers. Judging from the SO questions that seems to be rather complicated. So without some sample code i can't produce a working/sort-of-working example.
First of: I'm not sure if you want to actually connect to the database. The 'pure' form of unit testing tells you to work against a fake database (sqlite, in memomry) while I currently like to make sure my queries work against a real db instance so i test my databases access objects again the real db. Which brings me to the next point.
Your controller shouldn't talk to the database. Even (all/many) models talking directly to database is not what many people consider proper MVC but putting SQL in controllers is the php equivalent of putting html in your application-logic PHP code back in the php 4 days.
As a very general answer:
Look in the code where you get your $objectToMockOutInQuestion. When it comes from a method for constructor parameter you've won and you can just pass it in. When your code pulls it from a container see if you can but it in that container beforehand. If it's a plain old
new
operator you might want to change your code.Hope that helps even so it's only text