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 to mock services in DI (using codeception)?

So, after a few days of investigating I come here, and guess it's my last hope.

I try writing functional tests for my controllers using Codeception testing framework. I want to replace real service in DI with fake one.

Controller code example:

<?php

namespace App\Controllers;

class IndexController extends ControllerBase
{
  public function indexAction()
  {
    // some logic here
    $service = $this->getDI()->get('myService');
    $service->doSomething();
    // some logic here
  }
}

Test code example:

<?php

namespace App\Functional;

class IndexControllerCest
{
  public function testIndexAction()
  {
    // Here i want to mock myService, replace real object that in controller with fake one
  }
}

I already try different combinations with Codeception Phalcon module like addServiceToContainer. I setup Codeception using bootstrap.php file almost the same as for real app.

Phalcon version: 3.4.1 Codeception version: 3.1

So my question in last code fragment on comment section. Thank you for any help.

edited Dec '19

I think you should test myService code first from the rest of the piece.

To test your controller, it is better to make http calls and assert the response (status and body).

So looking at your code there are 2 separate tests you need to make.

  1. test myService code

  2. test myService code implementation alongside other code.

    I hope it helps.



10.1k

Have a look at the test inside Phalcon as well. There are some nice examples in there. https://github.com/phalcon/cphalcon/tree/master/tests