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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With