使用Laravel中的config app文件进行单元测试 [英] Unit testing with the config app file in Laravel

查看:249
本文介绍了使用Laravel中的config app文件进行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型方法依赖于此处的config()全局变量;

My model method relies on the config() global, here;

public function getGroup()
{
    if(config('app.pages.'.$this->group.'.0')) {
        return $this->group;
    }
    return "city";
}

我正在尝试在我的单元测试类中测试此方法;

I am trying to test this method in my unit test class, here;

public function testGetGroupReturnsCityAsDefault()
{
    $response = new Response();
    $response->group = "town";
    $test = $response->getGroup();
    dd($test);
}

我得到的错误是;

Error: Call to a member function make() on null
/home/vagrant/sites/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:62
/home/vagrant/sites/vendor/laravel/framework/src/Illuminate/Foundation/helpers.php:163

我知道这与config()全局有关.但不确定如何在测试中进行设置.我尝试过

I know this is related to the config() global. But not sure how to set it in my test. I tried

public function setUp()
{
config(['app.pages' => [
    'city' => [........

但是出现了同样的错误.我该如何设置?

But got the same error. How can I set this up?

推荐答案

我不确定您是否已解决此问题,但我遇到了类似的问题.

I'm not sure if you have solved this yet but I just had a similar issue.

要使其正常工作,我必须做两件事:

There were two things I had to do to get it to work:

1)确保像这样调用setUp父方法:

1) Make sure you are calling the setUp parent method like so:

public function setUp()
{
    parent::setUp();

    // other stuff
}

2)确保测试类正在扩展Laravel TestCase而不是PHPUnit_Framework_TestCase

2) Make sure your test class is extending the Laravel TestCase rather than the PHPUnit_Framework_TestCase

简要说明:基本上,您得到的错误是因为Laravel的ContainerInstance为空,因为您正在使用PHPUnit,因此从未创建过.如果执行上述步骤,则将确保Laravel首先实例化容器实例.

Brief explanation: Basically the error you are getting is because the ContainerInstance of Laravel is null since you are going through PHPUnit and as such it was never created. If you do the above steps you'll ensure that Laravel will first instantiate a container instance.

PS .如果最终要引用env变量,则应查看phpunit.xml部分中的环境变量.

P.S. If you are going to end up ultimately referencing env variables, you should look into the phpunit.xmlsection for enviornment variables.

这篇关于使用Laravel中的config app文件进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆