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

how use phpunit in phalcon.

I follow the official document use phpunit, but has error.

this is my code Directory

TestHelper.php code

    <?php
    //use Phalcon\Di;
    //use Phalcon\Di\FactoryDefault;
    ini_set('display_errors', 1);
    error_reporting(E_ALL);
    define('APP_PATH', __DIR__.'/../public');
    define('ROOT_PATH', __DIR__);
    define('PATH_LIBRARY', __DIR__ . '/../app/library/');
    define('PATH_SERVICES', __DIR__ . '/../app/services/');
    define('PATH_RESOURCES', __DIR__ . '/../app/resources/');
    set_include_path(
        ROOT_PATH . PATH_SEPARATOR . get_include_path()
    );
    // требуется для phalcon/incubator
    include __DIR__ . "/../vendor/autoload.php";
    // Используем автозагрузчик приложений для автозагрузки классов.
    // Автозагрузка зависимостей, найденных в composer.
    $loader = new \Phalcon\Loader();
    $loader->registerDirs(
        array(
            ROOT_PATH,
        )
    )->registerNamespaces(array(
        'MYH'             => '../app/library/',
        'App\Services'   => '../app/services/',
    ));
    $loader->register();

    if (!defined('PHPUNIT_COMPOSER_INSTALL')) {
        define('PHPUNIT_COMPOSER_INSTALL', __DIR__ . '/../vendor/autoload.php');
    }

UnitTestCase.php

    namespace Test;
if(!defined('APP_PATH'))
    define('APP_PATH', __DIR__.'/../public');

require_once  __DIR__ . "/TestHelper.php";

use Phalcon\Di;
use Phalcon\Loader;
use Phalcon\Test\UnitTestCase as PhalconTestCase;
use Phalcon\Config;
use Phalcon\Mvc\View;
use Phalcon\Mvc\View\Engine\Php as PhpEngine;
use Phalcon\Mvc\Url as UrlResolver;
use Phalcon\Mvc\View\Engine\Volt as VoltEngine;
use Phalcon\Mvc\Model\Manager as ModelsManager;
use Phalcon\Mvc\Model\Metadata\Memory as MetaDataAdapter;
use Phalcon\Session\Adapter\Files as SessionAdapter;
use Phalcon\Session\Adapter\Redis as SessionRedis;
use Phalcon\Flash\Direct as Flash;
use Phalcon\Mvc\Dispatcher;
use Phalcon\Mvc\Router;
use Phalcon\Events\Manager as EventsManager;
use Phalcon\Events\Event;
use Monolog\Handler\StreamHandler;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;
use Monolog\Formatter\LineFormatter;
use Phalcon\Http\Response;

abstract class UnitTestCase extends PhalconTestCase
{
    /**
     * @var bool
     */
    private $_loaded = false;

    public $logger;

    public function setUp()
    {
        parent::setUp();

        // Load any additional services that might be required during testing
        $di = Di::getDefault();

        // Get any DI components here. If you have a config, be sure to pass it to the parent
        $di->setShared('eventsManager', function () {
            $em = new EventsManager;
            $em->enablePriorities(true);

            return $em;
        });

        $di->setShared('logger', function () {
            $requestId = $this->getShared('requestId');
            $logger = new Monolog\Logger('App');
            $config = $this->getShared('config');
            //$streamHandler = new StreamHandler($config->logger->path . $config->logger->fileName, Logger::DEBUG);
            $streamHandler = new RotatingFileHandler($config->logger->path . $config->logger->fileName,30, Logger::DEBUG);
            $output = "[%datetime%][%channel%][requestId:{$requestId}][Level:%level_name%][Message:%message% %context% %extra%]\n";
            // finally, create a formatter
            $formatter = new LineFormatter($output);
            $streamHandler->setFormatter($formatter);
            $logger->pushHandler($streamHandler);
            return $logger;
        });

        $this->setDi($di);

        $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()."
            );
        }
    }
}

MqTaskTest.php

    namespace Test;

use PHPUnit\Framework\TestCase;
use Phalcon\Test\UnitTestCase as PhalconTestCase;

class MqTaskTest extends PhalconTestCase
{
    public function setUp()
    {
         parent::setUp(); // TODO: Change the autogenerated stub
    }

    public function testMqHandle()
    {
        $config = new \MYH\AliMq\Config(');
        $consumer = new \MYH\AliMq\HttpConsumer($config);
        //$data = $consumer->receiveMessage();

//        $this->logger->info('Receive Message:',[$data]);
//        echo "Receive Message Count:" .count($data['data']) ."\n";
//        if(empty($data['data'])) {
//        }
        $data = [
            'code' => '200',
            'data' => [
                'body' => '{"type":"sms","data":{"mobile":"18923405258","content":"\u4f60\u597d\u540c\u4e8b\uff0c\u6211\u662f\u6d4b\u8bd5\u6570\u636e"}}',
                'bornTime' => '1503459469659',
                'key' => 'http',
                'msgHandle'=> 'X1BFTkRJTkdNU0dfI21xLW1zZy1wdXNoLXRlc3QtdjEjcWRpbnRlcm5ldG9yZGVyLTAxIzAjMTgjQ0lEX2Jhc2VfYXBpX3YxX0BfQF8wQTk3Q0I0OTMzQTE1MzkxNEZFOTcxMzc5QjVCRDI4QV9AX0Bfakpw',
                'msgId' => '0A97CB4933A153914FE971379B5BD28A',
                'reconsumeTimes' => 0,
                'tag' => 'http'
                ]
        ];

        $mqService = new \App\Services\MqService();
        foreach ($data['data'] as $item) {
            $mqService->setData($item)->send();
            $consumer->deleteMessage($item['msgHandle']);
        }
    }
}

An error

Access to undefined property logger
 /Users/xxxx/code/xx/xxx/app/services/MqService.php:69
/Users/xxxx/code/xxx/xx/app/services/MqService.php:51
 /Users/xxxx/code/xxx/xxx/tests/MqTaskTest.php:49

that MqServer.php line 69 code

    public function initHandleObject()
  {
      $this->logger->info('MQ Receive Message:',[$this->data]);
      if(empty($this->data['body'])) {
          return false;
      }
      $body = json_decode($this->data['body'],true);
      $typeClass = $body['type'];
      $className = '\App\Services\Mq\\' . ucfirst(strtolower($typeClass)) . 'MqService';

      /**
       * @var MqInterface $mqClassObj;
       */
      $this->mqClassObj = new $className;

      return $this;
  }


85.5k

$this->getDI()->get("logger") ? i am no expert, but you can look at phalcon repo and copy paste from there https://github.com/phalcon/cphalcon/tree/master/tests/unit