簡體   English   中英

Laravel 包單元測試在配置文件中的輔助函數失敗(調用未定義的方法 base_path())

[英]Laravel package unit testing failing for helper function in config file (call to undefined method base_path())

好的,所以我正在嘗試更新一個我在 Laravel 4 上使用了很多的包以與 Laravel 5 兼容,因為原始存儲庫有一段時間沒有任何更新,它需要一些調整才能與 Laravel 一起使用5.

我已經進行了必要的更改,並創建了對原始存儲庫的拉取請求

不過,我注意到單元測試失敗了,所以我嘗試深入研究。 到目前為止,我還沒有對 PHPUnit 做過任何事情,所以我認為這將是一次很好的學習體驗。

我不是在尋求有關 github 上顯示的錯誤的幫助。 我設法克服了那個錯誤,但是我通過刪除一些測試來實現這一點,這當然不是一個實際的解決方案,因此這些更改沒有提交。 一旦我對單元測試的工作原理有了更好的理解,我就會解決這個問題。

我似乎遇到的問題是 Laravel 的一個輔助函數正在包的默認配置文件中使用,它說函數base_path()未定義。

據我了解,PHPUnit 與類一起工作,我需要模擬該函數才能使用它。 似乎無法找到直接的答案如何做到這一點。

由於它將配置變量指向我的存儲庫層次結構中不存在的文件夾,因此我什至不確定它應該返回什么。

導致問題的文件是位於 polyglot/config/polyglot.php 中的默認配置

return [

// Whether to swap out the facades (Router, Lang, etc) with
// Polyglot's, disable this if you need other packages to do the same
// Can specify an array of facades to swap, eg. ['Lang', 'URL']
'facades' => true,

// Locales
////////////////////////////////////////////////////////////////////

// The default locale if none is provided in the URL
// Leave empty to force the use of locales prefixes in URLs
'default' => 'en',

// The fallback locale for translations
// If null, the default locale is used
'fallback' => null,

// The available locales
'locales' => [],

// Gettext
////////////////////////////////////////////////////////////////////

// The domain of your translations, for gettext use
'domain' => 'messages',

// Where the PO/MO files reside

'folder' => base_path('resources/lang'),
// Format of the compiled files
'file' => '{domain}.po',

// Database
////////////////////////////////////////////////////////////////////

// The pattern Polyglot should follow to find the Lang classes
// Examples are "Lang\{model}", "{model}Lang", where {model}
// will be replaced by the model's name
'model_pattern' => '{model}Lang',

];

那么,在這種情況下,典型的做法是什么? 手動定義函數? 以某種方式包含幫助文件? 或者放棄使用該函數並使用基本的 php 目錄引用解決方案? 任何幫助,將不勝感激。

對於使用谷歌搜索的其他人,我找到的解決方案是使用CreatesApplication特征並在您的測試類中調用createApplication()方法。

class MyTest extends \PHPUnit\Framework\TestCase
{
   use Tests\CreatesApplication;

    protected function setUp(): void
    {
        $this->createApplication();
    }
}

將此添加到您的類后,您就可以訪問幫助類,如app()base_path()等。

base_path是一個標准的 Laravel 助手。 每次 Laravel 啟動時它都可用。 正確的方法是通過 Laravel 中包含的TestCase基類在測試中啟動 Laravel。 請參閱官方測試指南此 laracast

你不應該嘲笑這個方法。 您不應將其替換為文件引用和字符串程序集。 執行其中任何一項都會使代碼遠離Laravel 集成,而不是像您想要對 L5 升級所做的那樣。

暫無
暫無

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

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