编码测试时如何让 CodeIgnitor 3 自动加载?

我是 CI 的新手,正在努力了解它。


我熟悉 Laravel 和 Symfony,我发现测试 CI 代码非常困难。


我正在考虑使用服务定位器模式来尝试解决依赖注入限制,但现在我正在为自动加载而苦苦挣扎。


假设我有一个这样的模型:


<?php


class FooModel extends CI_Model

{        

    public function __construct()

    {

        parent::__construct();


        $this->load->library('alertnotificationservice');

    }

}

我想编写一个如下所示的测试:


<?php


namespace Test\AlertNotification;


// extends TestCase and offers reflection helper methods

use Test\TestBase;


class FooModelTest extends TestBase

{


    public function test_my_method()

    {

        $objectUnderTest = new \FooModel();

    }

}

当我运行我的测试时,我得到了错误Error: Class 'CI_Model' not found。


我正在使用 CodeIgnitor 3.1.2,它不使用 composer 或包含版本 4 手册引用的 phpunit.xml.dist 文件。


让自动加载发生以便我可以运行测试的“正确”方法是什么?


慕哥9229398
浏览 76回答 1
1回答

阿波罗的战车

我还没有找到令人满意的方法来做到这一点。我最终创建了一个bootstrap.php包含在 phpunit.xml.dist 中的文件它看起来像这样:<?phprequire(__DIR__ . '/../vendor/autoload.php');// this is a copy of the default index.php shipped with CodeIgnitor// The system and application_folder variables are replaced// Also, in this version we do not bootstrap the framework and rather include our own version belowrequire('loader.php');// this is a modified version of system/core/CodeIgniter.php// they do bootstrapping, routing, and dispatching in one place// so we can't use the whole file because dispatching fails when running testsrequire('framework.php');// set up the test environment database connectionputenv('DATABASE_HOST=localhost');putenv('DATABASE_USER=user');putenv('DATABASE_PASSWORD=password');putenv('DATABASE=control_panel');// CI uses a singleton approach and creates an instance of a child of this class during dispatch// We need to make sure that the singleton holder is populated$controller = new CI_Controller();这framework.php是该 CodeIgnitor 文件的精简版本,我在其中删除了路由和调度逻辑。我已经把这些文件作为要点CI 中加载的症结似乎存在于控制器中system/core/Controller.php,控制器旨在成为“让 CI 可以作为一个大型超级对象运行”的东西。该load_class函数(在 中声明system/core/Common.php)负责查找和加载类文件。我还应该包括我的composer.json文件。我正在使用它进行测试(CI 3.1.12 不使用作曲家){&nbsp; &nbsp; "require": {&nbsp; &nbsp; &nbsp; &nbsp; "guzzlehttp/guzzle": "^6.5"&nbsp; &nbsp; },&nbsp; &nbsp; "require-dev": {&nbsp; &nbsp; &nbsp; &nbsp; "phpunit/phpunit": "^9.1"&nbsp; &nbsp; },&nbsp; &nbsp; "autoload": {&nbsp; &nbsp; &nbsp; &nbsp; "psr-4": {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; "Test\\": "tests/"&nbsp; &nbsp; &nbsp; &nbsp; },&nbsp; &nbsp; &nbsp; &nbsp; "classmap": ["application/", "system/"]&nbsp; &nbsp; }}我真的很想避免加载所有东西,并希望能够模拟出点点滴滴,但我对 CodeIgnitor 适合这一点并不乐观。无论如何,这种方法至少可以让我启动我的应用程序。必须有更好的方法来做到这一点,如果很难正确测试,我不敢相信该框架会如此受欢迎。
打开App,查看更多内容
随时随地看视频慕课网APP