【发布时间】:2013-01-25 22:38:42
【问题描述】:
我正在学习单元测试,并试图解决以下问题:
Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for zfcUserAuthentication
...使用以下给出的唯一答案:
Simple ZF2 Unit Tests for a controller using ZfcUser
所以我的 setUp 函数看起来是一样的。不幸的是,我收到错误消息:
Zend\Mvc\Exception\InvalidPluginException: Plugin of type Mock_ZfcUserAuthentication_868bf824 is invalid; must implement Zend\Mvc\Controller\Plugin\PluginInterface
是在这部分代码引起的(在我的代码中也是这样拆分的):
$this -> controller->getPluginManager()
->setService('zfcUserAuthentication', $authMock); // Error refers to this line.
$authMock 对象显然没有实现插件接口,我需要实现它才能传递给 setService。
$authMock 不是为了在单元测试中使用而被传递到那里吗?我应该使用不同的(面向单元测试的)setService 方法吗?
我需要一种方法来处理登录到我的应用程序,否则我的单元测试毫无意义。
感谢您的建议。
=== 编辑 (11/02/2013) ===
我想把重点放在这部分进行澄清,因为我认为这是问题所在:
// Getting mock of authentication object, which is used as a plugin.
$authMock = $this->getMock('ZfcUser\Controller\Plugin\ZfcUserAuthentication');
// Some expectations of the authentication service.
$authMock -> expects($this->any())
-> method('hasIdentity')
-> will($this->returnValue(true));
$authMock -> expects($this->any())
-> method('getIdentity')
-> will($this->returnValue($ZfcUserMock));
// At this point, PluginManager disallows mock being assigned as plugin because
// it will not implement plugin interface, as mentioned.
$this -> controller->getPluginManager()
->setService('zfcUserAuthentication', $authMock);
如果 mock 没有处理必要的实现,我还能如何假装登录?
【问题讨论】:
-
我是否纠正了对控制器进行单元测试的必要性,因为它是模型?我发现这是我保存所有身份验证代码的地方。
-
我最近做了类似的事情,没有问题。你完整的测试用例类是什么样的?另外,您的测试引导程序是什么样的?最后是您尝试测试的操作。
-
单元测试时是否使用特殊的应用程序配置?在这种情况下,zfcUser 模块可能没有加载到测试环境中。
标签: phpunit zend-framework2 zfcuser