Ситуация: я тестирую действие контроллера 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)