Unit testing with the config app file in Laravel

2019-05-05 18:28发布

问题:

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);
}

The error I get is;

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

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?

回答1:

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) Make sure you are calling the setUp parent method like so:

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

    // other stuff
}

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

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.

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