Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Zend Framework 2 Controller Plugins unavailable in unit tests

Hi am an new to Zend all together and have been asked to develop with Z2. I am trying to add reusable functionality via controller plugins, but I am not having success with unit tests. It works fine inside the regular application.

// Application\Controller\Plugin\HelloWorld.php
namespace Application\Controller\Plugin;

use Zend\Mvc\Controller\Plugin\AbstractPlugin;
use Zend\Http\Client;
use Zend\Http\Request;

class HelloWorld extends AbstractPlugin
{

    public function helloWorld()
    {
        return "HELLO WORLD";
    }
}

// Application\Controller\IndexController.php
namespace Application\Controller;

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

class IndexController extends AbstractActionController
{

    public function indexAction()
    {
        echo $this->helloworld()->helloWorld();
    }
}

//Application\config\module.config.php
...
'controller_plugins' => array(
     'invokables' => array(
          'helloworld' => 'Application\Controller\Plugin\HelloWorld',
      ),
 ),
...

the error i get is:

Zend\ServiceManager\Exception\ServiceNotFoundException: Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for helloworld
like image 416
Juni Samos De Espinosa Avatar asked Oct 31 '12 00:10

Juni Samos De Espinosa


1 Answers

If you create a unit test for a controller, you test the controller in a dedicated, controlled unit. You do not initialize the application, you do not load the modules and you do not parse the complete configuration file.

To unit test the controller, add the plugin yourself in the setUp() method to put it as invokable directly in the service manager. If you want to test whether your configuration works, you are rather looking at functional testing. Try to bootstrap the complete application first and then test your controller by creating a request and asserting the response.

Because functional tests are a bit harder to solve, it is easier to start with controller (plugins) to test in a unit test:

namespace SlmLocaleTest\Locale;

use PHPUnit_Framework_TestCase as TestCase;
use Application\Controller\IndexController;

class IndexControllerTest extends TestCase
{
    public function setUp()
    {
        $controller = new IndexController;
        $controller->getPluginManager()
                   ->setInvokableClass('helloworld', 'Application\Controller\Plugin\HelloWorld');

        $this->controller = $controller;
    }

    public function testCheckSomethingHere()
    {
        $response = $this->controller->indexAction();
    }
}

You can replace setInvokableClass() by setService() to inject a mock for example.

like image 132
Jurian Sluiman Avatar answered Sep 25 '22 23:09

Jurian Sluiman