如何动态模拟Zfc用户服务

时间:2016-11-22 16:22:27

标签: php zend-framework2 phpunit zfcuser

情况:我正在测试Zend控制器操作,用户必须登录或以其他方式重定向:

<?php

namespace MyModule\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class GameController extends AbstractActionController
{
    public function indexAction()
    {
        if ($this->zfcUserAuthentication()->hasIdentity()) {
            $view = new ViewModel();
            $user = $this->zfcUserAuthentication()->getIdentity();
            $view->username = $user->getUsername();
            return $view;
        } else {
            $this->redirect()->toRoute("mymodule/overview");
        }
    }
}

我的测试用例看起来像这样:

<?php

namespace MyModuleTest\Controller;

use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
use ZfcUser\Controller\Plugin\ZfcUserAuthentication;
use ZfcUser\Entity\User;

class GameControllerTest extends AbstractHttpControllerTestCase
{
    public function setUp()
    {
        $this->setApplicationConfig(include __DIR__ . '/../../../../../config/application.config.php');
        parent::setUp();
    }

    public function testIndexAction()
    {
        // Mock the authentication user
        $user = $this->createMock(User::class);
        $user->expects($this->any())->method('getId')->will($this->returnValue('1'));

        // Mock the authentication adapter
        $authentication = $this->createMock(ZfcUserAuthentication::class);
        $authentication->expects($this->any())->method('hasIdentity')->will($this->returnValue(true));
        $authentication->expects($this->any())->method('getIdentity')->will($this->returnValue($user));

        $this->dispatch('/mymodule/game');
        $this->assertResponseStatusCode(302);
        $this->assertModuleName('MyModule');
        $this->assertMatchedRouteName('mymodule/game');
        $this->assertControllerName('MyModule\Controller\Game');
        $this->assertControllerClass('GameController');
        $this->assertActionName('index');

        // TODO: Log in the user
        // How do I install the mocked Zfc authentication?

        $this->dispatch('/mymodule/game');
        $this->assertResponseStatusCode(200);
        $this->assertModuleName('MyModule');
        $this->assertMatchedRouteName('mymodule/game');
        $this->assertControllerName('MyModule\Controller\Game');
        $this->assertControllerClass('GameController');
        $this->assertActionName('index');
    }
}

问题:有一些StackOverflow帖子如何模拟ZfcUser身份验证服务,但我该如何动态执行此操作(工作代码示例)?首先,我想触发重定向(并检查302 HTTP代码),然后我想登录用户(模拟它)并再次检查(并接收200 HTTP代码)

1 个答案:

答案 0 :(得分:0)

您应该在测试中模拟ZfcUser服务。测试ZfcUser的工作范围超出了应用程序的范围,并且在ZfcUser模块的测试中完成。例如,这里有302个错误:

ZfcUser/tests/ZfcUserTest/Controller/RedirectCallbackTest.php ZfcUser/src/ZfcUser/Controller/RedirectCallback.php ZfcUser/tests/ZfcUserTest/Controller/UserControllerTest.php

UPDATE:

因此,您的$this->zfcUserAuthentication()方法应该返回您准备的模拟类。这段代码不在问题中,所以我不能给你更多细节。 最好的方法是通过构造函数依赖注入注入ZfcUser身份验证服务(作为类构造函数中的依赖项)。