我尝试使用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
所以我的问题在注释部分的最后一个代码片段中。谢谢您的帮助。
答案 0 :(得分: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');
}
}