如何在 DI 中用模拟替换类?法尔康+密码



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

控制器代码示例:

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

测试代码示例:

<?php
namespace AppFunctional;
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。 我使用引导程序设置Codeception.php文件几乎与真实应用程序相同。

法尔康版本:3.4.1 编码版本:3.1

所以我在评论部分的最后一个代码片段中的问题。感谢您的任何帮助。

我建议您从创建一个单独的助手开始,以创建和注入依赖项,如下所示:

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

创建单独的服务:

<?php
namespace Helper;
use CodeceptionModule;
/** @var CodeceptionModulePhalcon */
protected $phalcon;
class MyService extends Module
{
public function _initialize()
{
$this->phalcon = $this->getModule('Phalcon');
}
public function haveMyServiceInDi()
{
$this->phalcon->addServiceToContainer(
'myService',
['className' => 'MyAwesomeService']
);
}
}

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

<?php
namespace AppFunctional;
use HelperMyService;
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');
}
}

最新更新