Home > database >  cant fill properties at __construct in laravel test unit
cant fill properties at __construct in laravel test unit

Time:06-01

I have created a simple test like this :

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use Illuminate\Support\Facades\Config;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class simpleTest extends TestCase
{
    public $form_array = ['forms_data'];


    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function test_example()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
}

The test above runs without a problem . I have a public property $form_array which in the example above has a static value, but when I'm trying to fill $form_array with __construct() in test, I get this error :

  array_merge(): Argument #1 must be of type array, null given

  at vendor/phpunit/phpunit/phpunit:98
     94▕ unset($options);
     95▕ 
     96▕ require PHPUNIT_COMPOSER_INSTALL;
     97▕ 
  ➜  98▕ PHPUnit\TextUI\Command::main();
     99▕ 

code :

namespace Tests\Feature;

use Tests\TestCase;
use App\Models\User;
use Illuminate\Support\Facades\Config;
use Illuminate\Foundation\Testing\WithFaker;
use Illuminate\Foundation\Testing\RefreshDatabase;

class simpleTest extends TestCase
{
    public $form_array;


    public function __construct(){

        $this->form_array = ['forms_data'];

    }


    /**
     * A basic feature test example.
     *
     * @return void
     */
    public function test_example()
    {
        $response = $this->get('/');

        $response->assertStatus(200);
    }
 }

My goal is fill the $form_data with values from config files in laravel which i found this way :

public function __construct(){
    parent::setUp();
    $this->form_array = Config::get('ravandro.form_array');
}

but even a simple $this->form_data = 'value' doesnt work , and im really confused !

btw , Im using Laravel Octane to serve my application but I dont think it has any effect to tests.

Php version : 8.1
Laravel : 9
php-unit: "phpunit/phpunit": "^9.3.3"

CodePudding user response:

In tests the correct constructor method is called setUp(), which runs before every test on that class.

You can check an example of this on https://phpunit.readthedocs.io/en/9.5/fixtures.html#fixtures

  • Related