简体   繁体   中英

Protected Properties PHP Laravel

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' => 'admin@gamil.nl',
            '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

create getter function for $data

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

unit test to test functions and not properties

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM