getServiceLocator在PHPUnittests下返回Null

时间:2016-05-23 20:06:47

标签: php zend-framework2 phpunit service-locator

我正在尝试测试一个简单的控制器,该控制器使用LdapAdapter验证用户并使用应用程序配置中的“ldap”数组,但phpunit返回以下错误:

Fatal error: Uncaught Error: Call to a member function get() on null in /var/www/html/app/module/Auth/src/Auth/Controller/AuthController.php:53
Stack trace:
#0 /var/www/html/app/module/Auth/test/AuthTest/Controller/AuthControllerTest.php(37): Auth\Controller\AuthController->authenticate('myuser', 'mypassword')
#1 [internal function]: AuthTest\Controller\AlbumControllerTest->testLoginAction()
#2 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(863): ReflectionMethod->invokeArgs(Object(AuthTest\Controller\AlbumControllerTest), Array)
#3 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(741): PHPUnit_Framework_TestCase->runTest()
#4 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestResult.php(608): PHPUnit_Framework_TestCase->runBare()
#5 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestCase.php(697): PHPUnit_Framework_TestResult->run(Object(AuthTest\Controller\AlbumControllerTest))
#6 /var/www/html/vendor/phpunit/phpunit/src/Framework/TestSuite.php(733): PHPUnit_Framework_TestCase- in /var/www/html/app/module/Auth/src/Auth/Controller/AuthController.php on line 53

我的控制器如下:

<?php

namespace Auth\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\Authentication\Adapter\Ldap as AuthAdapter;
use Zend\Authentication\AuthenticationService;
use Zend\Authentication\Result;
use Auth\Form\AuthForm;
use Auth\Model\Auth;


class AuthController extends AbstractActionController
{

    public function loginAction()
    {

        $form = new AuthForm();

        $request = $this->getRequest();
        if ($request->isPost()) {
            $auth = new Auth();

            $form->setInputFilter($auth->getInputFilter());
            $form->setData($request->getPost());

            if ($form->isValid()){
                $auth->exchangeArray($form->getData());

                $values = $form->getData();

                $result = $this->authenticate($values['username'], $values['password']);

                switch($result->getCode()) {

                    case Result::SUCCESS:
                        return $this->redirect()->toRoute('home');
                        break;

                    case Result::FAILURE:
                        break;
                    }
                }

            }
        return array('form' => $form);

        }

    public function authenticate($username, $password){

        $options = $this->getServiceLocator()->get('Config');

        $authAdapter = new AuthAdapter($options['ldap'],
            'username',
            'password');

        $authAdapter
            ->setIdentity($username)
            ->setCredential($password);

        $auth = new AuthenticationService();

        $result = $auth->authenticate($authAdapter);

        return $result;
    }

    private function debug($var){
        echo '<pre>';
        var_dump($var);
        echo '</pre>';
        exit();
    }
}

The TestCase:

namespace AuthTest\Controller;

use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;
use Zend\Authentication\AuthenticationService;
use Auth\Controller\AuthController;


class AuthControllerTest extends AbstractHttpControllerTestCase
{
    protected $traceError = true;

    public function setUp()
    {
        $this->setApplicationConfig(
            include '/var/www/html/app/config/application.config.php'
        );
        parent::setUp();
    }

    public function testLoginAction()
    {
        #Basic Access to the page
        $this->dispatch('/login');
        $this->assertResponseStatusCode(200);

        $data = array(
            'identity' => 'myuser',
            'credential' => 'mypassword',
        );

        $auth = new AuthController();
        $auth->authenticate($data['identity'], $data['credential']);

        $identity = new AuthenticationService();
        $this->assertEquals($data['identity'], $identity->getIdentity());
    }
}

PHPUnittest的BootStrap:

<?php

namespace AuthTest;

use Zend\Loader\AutoloaderFactory;
use Zend\Mvc\Service\ServiceManagerConfig;
use Zend\ServiceManager\ServiceManager;
use RuntimeException;

error_reporting(E_ALL | E_STRICT);
chdir(__DIR__);

/**
 * Test bootstrap, for setting up autoloading
 */
class Bootstrap
{
    protected static $serviceManager;

    public static function init()
    {
        $zf2ModulePaths = array(dirname(dirname(__DIR__)));
        if (($path = static::findParentPath('vendor'))) {
            $zf2ModulePaths[] = $path;
        }
        if (($path = static::findParentPath('module')) !== $zf2ModulePaths[0]) {
            $zf2ModulePaths[] = $path;
        }

        static::initAutoloader();

        // use ModuleManager to load this module and it's dependencies
        $config = array(
            'module_listener_options' => array(
                'module_paths' => $zf2ModulePaths,
            ),
            'modules' => array(
                'Auth'
            )
        );

        $serviceManager = new ServiceManager(new ServiceManagerConfig());
        $serviceManager->setService('ApplicationConfig', $config);
        $serviceManager->get('ModuleManager')->loadModules();
        static::$serviceManager = $serviceManager;
    }

    public static function chroot()
    {
        $rootPath = dirname(static::findParentPath('module'));
        chdir($rootPath);
    }

    public static function getServiceManager()
    {
        return static::$serviceManager;
    }

    protected static function initAutoloader()
    {
        $vendorPath = static::findParentPath('vendor');

        if (file_exists($vendorPath.'/autoload.php')) {
            include $vendorPath.'/autoload.php';
        }

        if (! class_exists('Zend\Loader\AutoloaderFactory')) {
            throw new RuntimeException(
                'Unable to load ZF2. Run `php composer.phar install`'
            );
        }

        AutoloaderFactory::factory(array(
            'Zend\Loader\StandardAutoloader' => array(
                'autoregister_zf' => true,
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/' . __NAMESPACE__,
                ),
            ),
        ));
    }

    protected static function findParentPath($path)
    {
        $dir = __DIR__;
        $previousDir = '.';
        while (!is_dir($dir . '/' . $path)) {
            $dir = dirname($dir);
            if ($previousDir === $dir) {
                return false;
            }
            $previousDir = $dir;
        }
        return $dir . '/' . $path;
    }
}

Bootstrap::init();
Bootstrap::chroot();

在功能测试中,它按预期工作,但在php unittests上,错误发生在第53行'$ options = $ this-&gt; getServiceLocator() - &gt; get('Config');'。

那么,如何使用或设置ServiceLocator来处理phpunittests?

1 个答案:

答案 0 :(得分:0)

在对使用ServiceLocator的控制器的这个疑问和其他测试进行了如此多的努力之后,我认为测试控制器Action的正确方法是模拟对象或/和他的方法。

我对这个解决方案感到不舒服,但就目前而言,这就是它。

另一种感觉是,模仿代码的行为就像破坏了DRY原则:不使用真正的代码,而只是创建一个半成像的模拟:S

无论如何,以下代码为我完成了这项工作:

    $authControllerMock = $this->getMockBuilder('Auth\Controller\AuthController')
        ->disableOriginalConstructor()
        ->getMock();

    $authControllerMock->expects($this->any())
        ->method('authenticate')
        ->will($this->returnValue(true);

    $serviceManager = $this->getApplicationServiceLocator();
    $serviceManager->setAllowOverride(true);
    $serviceManager->setService('Auth\Controller\Auth', $authControllerMock);

    $this->dispatch('/usermgr');

    self::assertMatchedRouteName('usermgr');
    self::assertControllerClass('AuthController');
    self::assertControllerName('auth\controller\auth');
    self::assertResponseStatusCode('200');