We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Testing phalcon Application with PHPUnit

Hi,

First I wanna say that my english is not very good, and I am a beginner in PHP and Phalcon and I need some help, so, be patient please, I thank you in advance.

I am developing a set of functions to make operations into mysql database, and i'd like to test them with phpunit. I tested some functions that don't have database connection (arrays, strings, ...). But when I test some function that consult the database, i've the following error:

Exception: Serialization of 'Phalcon\DI\FactoryDefault' is not allowed

The funny is that if i call the function in the index.php, for example, it returns correctly.

The code is here: (php 5.5.9) (ubuntu 14.04) (PHPUnit 4.4.1) (Phalcon DevTools (1.3.4))

index.php

<?php
$loader = new \Phalcon\Loader ();

$loader->registerDirs ( array ( __DIR__ . '/models/' ) )->register ();

$di = new \Phalcon\DI\FactoryDefault ();

$di->set ( 'db', function () {
    return new \Phalcon\Db\Adapter\Pdo\Mysql ( array (
            "host" => "localhost",
            "username" => "user",
            "password" => "pass",
            "dbname" => "my_db",
            "charset" => "utf8" 
    ) );
} );

function getAll() {
    global $di;

    $phql = "SELECT * FROM Table ORDER BY name";
    $query = new Phalcon\Mvc\Model\Query ( $phql, $di );
    $categorias = $query->execute ();

    $data = array ();
    foreach ( $categorias as $categ ) {
        $data [] = array (
                'id' => $categ->id,
                'name' => $categ->name,
        );
    }

    echo json_encode ( $data );
}
?>

and the test class:

<?php

use PHPUnit_Framework_TestCase as PHPUnit;

require "src/Application/index.php";

class Test extends PHPUnit {
    public function setUp() {
    }
    public function tearDown() {
    }
    function testA() {
    }
}

?>

After I tried other mode, I get this error: Phalcon\Mvc\Model\Exception: dependency Injector is required to get 'modelsManager' service

Someone knows how to resolve this?



2.8k
Accepted
answer

Take a look at Phalcon Incubator And a wiki guide to use a PHPUnit



2.2k

Your code in your post is difficult to read. Would you please fix the markdown?

See "Code Blocks" in https://forum.phalcon.io/help/markdown

edited Jan '15

Post fixed. I'm sorry.

I used and it's not working.

$loader = new \Phalcon\Loader ();

$loader->registerDirs ( array (
        __DIR__ . '/models/' 
) )->register ();

$loader->registerNamespaces(array(
        'Phalcon' => "~/incubator/"
));

$loader->register();

Exception: Serialization of 'Phalcon\DI\FactoryDefault' is not allowed