I'm trying to set up unittests, but I'm having no luck at all. I created TestHelper.php in a tests folder. This file looks like this:
<?php
use PhalconDi;
use PhalconDiFactoryDefault;
ini_set('display_errors',1);
error_reporting(E_ALL);
define('ROOT_PATH', __DIR__);
define('PATH_LIBRARY', __DIR__ . '/../app/library/');
define('PATH_SERVICES', __DIR__ . '/../app/services/');
define('PATH_RESOURCES', __DIR__ . '/../app/resources/');
define('BASE_DIR', diame(__DIR__));
define('APP_DIR', BASE_DIR . '/app');
set_include_path(
ROOT_PATH . PATH_SEPARATOR . get_include_path()
);
// Required for phalcon/incubator
include __DIR__ . "/../vendor/autoload.php";
// Use the application autoloader to autoload the classes
// Autoload the dependencies found in composer
$loader = new PhalconLoader();
$loader->registerDirs(
array(
ROOT_PATH
)
);
$config = include APP_DIR . '/config/config.php';
$loader->registerNamespaces(array(
'MyAppModels' => $config->application->modelsDir,
'MyAppControllers' => $config->application->controllersDir,
'MyAppForms' => $config->application->formsDir,
'MyAppClasses' => $config->application->classesDir,
'MyApp' => $config->application->libraryDir
));
$loader->register();
I also created UnitTestCase.php:
<?php
use PhalconDi;
use PhalconDIFactoryDefault;
use PhalconTestUnitTestCase as PhalconTestCase;
use PhalconMvcView;
use PhalconCrypt;
use PhalconMvcDispatcher;
use PhalconMvcDispatcher as PhDispatcher;
use PhalconMvcUrl as UrlResolver;
use PhalconDbAdapterPdoMysql as DbAdapter;
use PhalconMvcViewEngineVolt as VoltEngine;
use PhalconMvcModelMetadataFiles as MetaDataAdapter;
use PhalconSessionAdapterFiles as SessionAdapter;
use PhalconFlashDirect as Flash;
use PhalconLogger;
use PhalconEventsManager as EventsManager;
use PhalconLoggerAdapterFile as LoggerFile;
use MyAppAuthAuth;
use MyAppAuthPublicAuthPublic;
use MyAppAclAcl;
use MyAppCacheDataCacheData;
use MyAppMailMail;
use MyAppPHPExcelPHPExcel;
abstract class UnitTestCase extends PhalconTestCase
{
/**
* @var VoiceCache
*/
protected $_cache;
/**
* @var PhalconConfig
*/
protected $_config;
/**
* @var bool
*/
private $_loaded = false;
public function setUp(PhalconDiInterface $di = NULL, PhalconConfig $config = NULL)
{
// Load any additional services that might be required during testing
$di = new FactoryDefault();
$config = include APP_DIR . '/config/config.php';
/**
* The URL component is used to generate all kind of urls in the application
*/
$di->set('url', function () use ($config) {
$url = new UrlResolver();
$url->setBaseUri($config->application->baseUri);
retu $url;
}, true);
/**
* Setting up the view component
*/
$di->set('view', function () use ($config) {
$view = new View();
$view->setViewsDir($config->application->viewsDir);
$view->registerEngines(array(
'.volt' => function ($view, $di) use ($config) {
$volt = new VoltEngine($view, $di);
$volt->setOptions(array(
'compiledPath' => $config->application->cacheDir . 'volt/',
'compiledSeparator' => '_'
));
retu $volt;
}
));
retu $view;
}, true);
/**
* Database coection is created based in the parameters defined in the configuration file
*/
$di->set('db', function () use ($config) {
$eventsManager = new EventsManager();
// Debug sql logging //
$is_debug_sql_logging = true;
if ( $is_debug_sql_logging )
{
$logger = new LoggerFile( $config->application->logsDir ."debug_sql.log" );
$logger->log( "n------n" );
// Listen all the database events //
$eventsManager->attach( 'db', function( $event, $coection ) use ($logger) {
if ( $event->getType() == 'beforeQuery' ) {
$log_message = $coection->getRealSQLStatement()."n".print_r( $coection->getSQLVariables(), true );
$logger->log( $log_message, Logger::DEBUG );
}
if ($event->getType() == 'afterQuery') {
//...//
}
});
}
// Database coection //
$dbAdapter = new DbAdapter(array(
'host' => 'localhost',
'useame' => 'root',
'password' => 'root',
'dbname' => 'database'
));
//Assign the eventsManager to the db adapter instance
$dbAdapter->setEventsManager( $eventsManager );
retu $dbAdapter;
});
/**
* If the configuration specify the use of metadata adapter use it or use memory otherwise
*/
$di->set('modelsMetadata', function () use ($config) {
retu new MetaDataAdapter(array(
'metaDataDir' => $config->application->cacheDir . 'metaData/'
));
});
$di->set('modelsManager', function() {
retu new PhalconMvcModelManager();
});
/**
* Start the session the first time some component request the session service
*/
$di->set('session', function () {
$session = new SessionAdapter();
$session->start();
retu $session;
});
/**
* Cache of models
*/
$di->set('cache', function () {
$cacheData = new CacheData();
retu $cacheData;
});
/**
* Crypt service
*/
$di->set('crypt', function () use ($config) {
$crypt = new Crypt();
$crypt->setKey($config->application->cryptSalt);
retu $crypt;
});
/**
* Set a 404 redirect AND use a default namespace
*/
$di->set('dispatcher', function() use ($di) {
$evManager = $di->getShared('eventsManager');
$evManager->attach(
"dispatch:beforeException",
function($event, $dispatcher, $exception)
{
switch ($exception->getCode()) {
case PhDispatcher::EXCEPTION_HANDLER_NOT_FOUND:
case PhDispatcher::EXCEPTION_ACTION_NOT_FOUND:
$dispatcher->forward(
array(
'controller' => 'error',
'action' => 'show404',
)
);
retu false;
}
}
);
$dispatcher = new PhDispatcher();
$dispatcher->setEventsManager($evManager);
/* Dispatcher use a default namespace */
$dispatcher->setDefaultNamespace('MyAppControllers');
retu $dispatcher;
},
true
);
/**
* Loading routes from the routes.php file
*/
$di->set('router', function () {
retu require __DIR__ . '/routes.php';
});
/**
* Flash service with custom CSS classes
*/
$di->set('flash', function () {
retu new Flash(array(
'error' => 'notification notification--error',
'success' => 'notification notification--success',
'notice' => 'notification notification--neutral',
'general' => 'notification notification--general',
'waing' => 'notification notification--waing'
));
});
/**
* Authentication component
*/
$di->set('auth', function () {
retu new Auth();
});
/**
* Self test authentication component
*/
$di->set('authPublic', function () {
retu new AuthPublic();
});
/**
* Mail service uses AmazonSES
*/
$di->set('mail', function () {
retu new Mail();
});
/**
* Access Control List
*/
$di->set('acl', function () {
retu new Acl();
});
/**
* PHPExcel
*/
$di->set('phpexcel', function () {
retu new PHPExcel();
});
parent::setUp($di, $config);
$this->_loaded = true;
}
/**
* Check if the test case is setup properly
*
* @throws PHPUnit_Framework_IncompleteTestError;
*/
public function __destruct()
{
if (!$this->_loaded) {
throw new PHPUnit_Framework_IncompleteTestError('Please run parent::setUp().');
}
}
}
And also phpunit.xml:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit bootstrap="TestHelper.php"
backupGlobals="false"
backupStaticAttributes="false"
verbose="true"
colors="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWaingsToExceptions="true"
processIsolation="false"
stopOnFailure="false"
syntaxCheck="true">
<testsuite name="Phalcon - Testsuite">
<directory>./</directory>
</testsuite>
</phpunit>
All this together, should make me able to run some unittests. However, when I go to the tests folder in terminal and run ../vendor/bin/phpunit it throws an error. The error is PhalconDiException: Service 'modelsManager' wasn't found in the dependency injection container. I have been struggling for some hours with this and I hope someone will be able to help me. What am I doing wrong here?
