Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing with the config app file in Laravel

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?

like image 819
mikelovelyuk Avatar asked Jan 27 '16 15:01

mikelovelyuk


People also ask

What is unit testing in Laravel 8?

Unit tests are tests that focus on a very small, isolated portion of your code. In fact, most unit tests probably focus on a single method. Tests within your "Unit" test directory do not boot your Laravel application and therefore are unable to access your application's database or other framework services.

What is the most popular testing framework used with Laravel?

Many PHP frameworks have their own ORM built-in. For example, Laravel uses the Eloquent ORM.


1 Answers

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
}
  1. 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 environment variables.

like image 96
tam5 Avatar answered Sep 28 '22 00:09

tam5