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

PHPUnit, DI only available in first TestCase?

I followed this guide to set up PHPUnit tests. I added 'config', 'db', 'mongo' and some others to the DI like this:

$di->set('config', function () use ($config) {
  return include '../include/config.php'; // Retruns \Phalcon\Config Instance
}, true);

In The first TestCase I can execute $this->getDI()->get("config"), but in any following TestCase I get Service "config" wasn´t found in the dependency injection container. A Vardump of $this->getDI() in the second TestCase looks like a clean default DI without 'config', 'mongo', 'db' and so on...

I tried a little workaround by modifing the \UnitTestCase:

  public function setUp(\Phalcon\DiInterface $di = NULL, \Phalcon\Config $config = NULL) {

    // $dix is defined in TestHelper.php: $dix = include __DIR__ . "/../include/di.php";
    // which returns a "\Phalcon\DI\FactoryDefault()"
    global $dix;
    $di = $dix;

    // 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
    parent::setUp($di);

    $this->_loaded = true;
  }

Now the other Tests will run, but as soon as I access any Model I get:

1) MyService\Route\UserTest::testSignupValidation
Phalcon\Mvc\Model\Exception: A dependency injector container is required to obtain the services related to the ORM

Thanks for any ideas... ;)



34.6k
Accepted
answer

You can include the code or the file that initializes the di in every setUp:

public function setUp(\Phalcon\DiInterface $di = NULL, \Phalcon\Config $config = NULL)
{

    $di = new \Phalcon\Di\FactoryDefault;

    $di->set('config', function () use ($config) {
  return include '../include/config.php'; // Retruns \Phalcon\Config Instance
}, true);

    // get any DI components here. If you have a config, be sure to pass it to the parent
    parent::setUp($di);

    $this->_loaded = true;
  }


1.1k

Hm, I couldn't see the forest for the trees ;) Thanks a lot, now it works.