繁体   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