Как динамически издеваться над пользовательским сервисом Zfc

Ситуация: я тестирую действие контроллера 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, но как я могу сделать это динамически (пример рабочего кода)? Во-первых, я хочу вызвать перенаправление (и проверить HTTP-код 302), затем я хочу войти в систему пользователя (издеваться над ним) и снова проверить его (и получить HTTP-код 200)


person swaechter    schedule 22.11.2016    source источник


Ответы (1)


Вы должны издеваться над сервисом ZfcUser в своих тестах. Тестирование работы ZfcUser выходит за рамки вашего приложения и выполняется в тестах для модуля ZfcUser. Например здесь для 302 ошибки:

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

ОБНОВИТЬ:

Таким образом, ваш метод $this->zfcUserAuthentication() должен возвращать подготовленный вами издевательский класс. Эта часть вашего кода не входит в вопрос, поэтому я не могу дать вам более подробную информацию об этом. Лучше всего было бы внедрить службу аутентификации ZfcUser через внедрение зависимостей конструктора (как зависимость в конструкторе вашего класса).

person Wilt    schedule 23.11.2016
comment
Я отредактировал свой ответ и добавил издевательского пользователя и аутентификацию - как вы сказали. Но проблема в том, что я не знаю, как установить/внедрить издевательский объект в Zend - person swaechter; 23.11.2016
comment
Вы должны издеваться над методом $this->zfcUserAuthentication(), чтобы вернуть макет... - person Wilt; 23.11.2016