簡體   English   中英

編碼測試時如何讓 CodeIgnitor 3 自動加載?

[英]How to get CodeIgnitor 3 to autoload when coding tests?

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

我熟悉 Laravel 和 Symfony,我發現測試 CI 代碼非常困難。

我正在考慮使用服務定位器模式來嘗試解決依賴注入限制,但現在我正在努力解決自動加載問題。

假設我有這樣的 model:

<?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,它不使用作曲家,也不包含第 4 版手冊中提到的 phpunit.xml.dist 文件。

什么是讓自動加載發生的“正確”方法,以便我可以運行我的測試?

我還沒有找到令人滿意的方法來做到這一點。 我最終創建了一個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和 controller 旨在讓“以便 CI 可以作為一個大型超級對象運行”的東西。 load_class function(在system/core/Common.php中聲明)負責查找和加載 class 文件。

我還應該包括我的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 適合這一點。

無論如何,這種方法至少可以讓我啟動我的應用程序。 必須有更好的方法來做到這一點,如果很難正確測試,我無法相信該框架會如此受歡迎。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM