Home > Enterprise >  Protected Properties PHP Laravel
Protected Properties PHP Laravel

Time:09-20

How can access properties of a protected object PHP while writing tests. Below is my sample code. TestCase.php The test fails to run saying that the property is protected. But it can die dumped.

<?php

namespace Tests;

use Illuminate\Http\Response;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    public function getAuthUser()
    {
        $payload = [
            'email' => '[email protected]',
            'password' => 'password',
        ];
       return $this->json('post', 'api/v1/auth/login', $payload)
             ->assertStatus(Response::HTTP_OK);
    }
}

my sample test

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Http\Response;

class PatientsControllerTest extends TestCase
{
    /**
     * A basic unit test patient controller.
     *
     * @return void
     */
    public function testPatientFetch()
    {
        $auth_user =  $this->getAuthUser();
        dd($auth_user->data);
    }
}

my sample code

<?php

namespace Tests\Unit;

use Tests\TestCase;
use Illuminate\Http\Response;

class PatientsControllerTest extends TestCase
{
    /**
     * A basic unit test patient controller.
     *
     * @return void
     */
    public function testPatientFetch()
    {
        $auth_user =  $this->getAuthUser();
        dd($auth_user->data);
    }
}

Error received

       FAIL  Tests\Unit\PatientsControllerTest
  ⨯ patient fetch

  ---

  • Tests\Unit\PatientsControllerTest > patient fetch
   PHPUnit\Framework\ExceptionWrapper 

  Cannot access protected property Illuminate\Http\JsonResponse::$data

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



  Tests:  1 failed
  Time:   1.05s

CodePudding user response:

create getter function for $data

public function get_data(){
   return $this->data;
}

unit test to test functions and not properties

CodePudding user response:

You can access and manipulate protected variables with ReflectionClass.

Please try this:

$user = $this->getAuthUser();
$reflectionClass = new ReflectionClass($user);
//If we assume we have a protected variable $data we can get access it with Reflection Class
$property = $reflectionClass->getProperty('data');
$property->setAccessible(true); //Here we are making protected variables accessible
$property->setValue($user, 'New Protected Data');
  • Related