如何在DI中用模拟代替类? Phalcon + Codeception

问题描述 投票:0回答:1

我尝试使用Codeception测试框架为我的控制器编写功能测试。我想用假的代替DI中的真实服务。

控制器代码示例:

<?php

namespace App\Controllers;

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

测试代码示例:

<?php

namespace App\Functional;

class IndexControllerCest
{
  public function testIndexAction(FunctionalTester $I)
  {
    // Here i want to mock myService, replace real object that in controller with fake one
    $I->amOnRoute('index.route');
  }
}

我已经尝试使用Codeception Phalcon模块(例如addServiceToContainer)进行不同的组合。我使用bootstrap.php文件设置Codeception与实际应用程序几乎相同。

Phalcon版本:3.4.1密码接收版本:3.1

所以我在注释部分的最后代码片段中的问题。谢谢您的帮助。

dependency-injection phalcon codeception
1个回答
0
投票

我建议您从创建单独的帮助程序开始,如下创建和注入依赖项:

# functional.suite.yml
class_name: FunctionalTester
modules:
    enabled:
        - Helper\MyService
        - Phalcon:
            part: services
            # path to the bootstrap
            bootstrap: 'app/config/bootstrap.php'
        # Another modules ...

创建单独的服务:

<?php
namespace Helper;

use Codeception\Module;

/** @var \Codeception\Module\Phalcon */
protected $phalcon;

class MyService extends Module
{
  public function _initialize()
  {
      $this->phalcon = $this->getModule('Phalcon');
  }

  public function haveMyServiceInDi()
  {
    $this->phalcon->addServiceToContainer(
      'myService',
      ['className' => '\My\Awesome\Service']
    );
  }
}

并按如下所示在测试中使用它:

<?php
namespace App\Functional;

use Helper\MyService;

class IndexControllerCest
{
  /** @var MyService */
  protected $myService;

  protected function _inject(MyService $myService)
  {
      $this->myService = $myService;
  }

  public function testIndexAction(FunctionalTester $I)
  {
    $I->wantTo(
      'mock myService, replace real object that in controller with fake one'
    );

    $this->myService->haveMyServiceInDi();
    $I->amOnRoute('index.route');
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.