亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

編碼測試時如何讓 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 關注
  • 129 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號