Zend Framework 2:AbstractControllerTestCase和ZfcUser,ZfcRbac

时间:2015-03-30 07:00:15

标签: zend-framework2 phpunit integration-testing

目前我们正在使用PHPUnit测试ZF2应用程序。在本应用程序中,我们使用模块ZFCUser和ZFCRbac。

我们有一个后端,受ZfcRbac-RouteGuards保护。我们还希望使用登录用户在Controller中测试“后端”-Action。 是否有可能在AbstractControllerTestCase中模拟用户?

亲切的问候,

Cwan

更多信息:

控制器:

<?php
namespace Application\Controller;

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

class IndexController extends AbstractActionController
{
    public function indexAction()
    {
        return new ViewModel();
    }

    public function backendAction()
    {
        return new ViewModel();
    }
}

ControllerTest:

<?php
namespace ApplicationTest\Controller;

use Zend\Test\PHPUnit\Controller\AbstractControllerTestCase;

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

    public function testIndexAction()
    {
        $this->dispatch('/');

        $this->assertResponseStatusCode(200);
        $this->assertModuleName('Application');
        $this->assertControllerName('Application\Controller\IndexController');
        $this->assertControllerClass('IndexController');
        $this->assertActionName('index');
        $this->assertMatchedRouteName('home');
    }

    public function testBackendAction()
    {
        $this->dispatch('/backend');

        $this->assertResponseStatusCode(403);
        $this->assertModuleName('Application');
        $this->assertControllerName('Application\Controller\IndexController');
        $this->assertControllerClass('IndexController');
        $this->assertActionName('backend');
        $this->assertMatchedRouteName('backend');
    }
}

后卫:

'guards' => [
    'ZfcRbac\Guard\RouteGuard' => [
        'home'    => ['*'],
        'backend' => ['admin'],
    ],
],

路线:

'router' => array(
    'routes' => array(
        'home' => array(
            'type' => 'Zend\Mvc\Router\Http\Literal',
            'options' => array(
                'route' => '/',
                'defaults' => array(
                    'controller' => 'Application\Controller\IndexController',
                    'action' => 'index'
                )
            )
        ),
        'backend' => array(
            'type' => 'Zend\Mvc\Router\Http\Literal',
            'options' => array(
                'route' => '/backend',
                'defaults' => array(
                    'controller' => 'Application\Controller\IndexController',
                    'action' => 'backend'
                )
            )
        )
    )
)

1 个答案:

答案 0 :(得分:1)

https://github.com/ZF-Commons/zfc-rbac/pull/298是一个补丁,可以帮助测试受zfcrbac路由保护保护的Zend Framework 2控制器。