为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

PHP
慕哥9229398 2023-04-28 14:10:59
我是 CI 的新手,正在努力了解它。我熟悉 Laravel 和 Symfony,我发现测试 CI 代码非常困难。我正在考虑使用服务定位器模式来尝试解决依赖注入限制,但现在我正在为自动加载而苦苦挣扎。假设我有一个这样的模型:<?phpclass FooModel extends CI_Model{            public function __construct()    {        parent::__construct();        $this->load->library('alertnotificationservice');    }}我想编写一个如下所示的测试:<?phpnamespace Test\AlertNotification;// extends TestCase and offers reflection helper methodsuse 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 文件。让自动加载发生以便我可以运行测试的“正确”方法是什么?
查看完整描述

1 回答

?
阿波罗的战车

TA贡献1862条经验 获得超6个赞

我还没有找到令人满意的方法来做到这一点。我最终创建了一个bootstrap.php包含在 phpunit.xml.dist 中的文件


它看起来像这样:


<?php


require(__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 below

require('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 tests

require('framework.php');


// set up the test environment database connection

putenv('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 不使用作曲家)


{

    "require": {

        "guzzlehttp/guzzle": "^6.5"

    },

    "require-dev": {

        "phpunit/phpunit": "^9.1"

    },

    "autoload": {

        "psr-4": {

            "Test\\": "tests/"

        },

        "classmap": ["application/", "system/"]

    }

}

我真的很想避免加载所有东西,并希望能够模拟出点点滴滴,但我对 CodeIgnitor 适合这一点并不乐观。


无论如何,这种方法至少可以让我启动我的应用程序。必须有更好的方法来做到这一点,如果很难正确测试,我不敢相信该框架会如此受欢迎。


查看完整回答
反对 回复 2023-04-28
  • 1 回答
  • 0 关注
  • 72 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信