Morpheus_ro Morpheus_ro - 23 days ago 19
PHP Question

PHPUnit testing ZF2 fail on model

I am trying to make a simple Unit test over this code:

class IndexController extends CommonController
{
public function indexAction()
{
$this->layout('layout/layouthome');
$language = $this->getLanguage($this->params('language'));

$sm = $this->getServiceLocator();
$tests = $sm->get('Tests');
$users = $sm->get('Users');

$this->layout()->language = substr($language, 0, 2);
$translations = $this->getTranslations($sm, $language);
$this->layout()->getAllTranslationByLocale = $translations;

$userSession = $this->loginService->getSessionUser();

if (!empty($userSession)) {
$this->redirectUser($userSession, $language);
}

return new ViewModel(array(
'translations' => $translations,
'language' => $language,
'getAllJobsByTopjobs' => $tests->getAllTestsByTopTests(),
'countAllUsers' => $users->countAllUsers(),
));
}
}


and my simple test is like this:

<?php namespace ApplicationTest\Controller;

use Zend\Stdlib\ArrayUtils;
use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;

class LogoutTest extends AbstractHttpControllerTestCase
{
protected $traceError = true;

public function setUp()
{
parent::setUp();
$configOverrides = [];

$this->setApplicationConfig(ArrayUtils::merge(
// Grabbing the full application configuration:
include __DIR__ . '/../../../../../config/application.config.php',
$configOverrides
));

}

public function testIndexActionCanBeAccessed()
{
$this->dispatch('/');
$this->assertResponseStatusCode(200);
}
}


The issue that I have is I can't instantiate the Tests and Users model. I am new to ZF2 and also to Unit tests, so any help is much appreciated. Thank you

Answer

I'll need to see more of the code for your test, but if you're using a zend based phpunit class you'll need to setup your config, an example below:

namespace Something;

use Zend\Test\PHPUnit\Controller\AbstractHttpControllerTestCase;

class SomethingTest extends AbstractHttpControllerTestCase
{ 
    public function setUp()
    {
        // now the tests know how to load your config and
        // services / service manager etc.
        // this may be your main config or a test specific config
        $this->setApplicationConfig(
           include __DIR__ . '/../../config/application.config.test.php'
        );
    }

    public function testIndexActionCanBeAccessed()
    {
        // access via application object..
        $bla = $this->getApplication()->getServiceManager()->get('Tests');

        $this->dispatch('/');
        $this->assertResponseStatusCode(200);
    }

}
Comments