繁体   English   中英

受保护的属性 PHP Laravel

[英]Protected Properties PHP Laravel

如何在编写测试时访问受保护的 object PHP 的属性。 下面是我的示例代码。 TestCase.php 测试未能运行,表明该属性受到保护。 但它可能会死掉。

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

我的样本测试

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

我的示例代码

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

收到错误

       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

为 $data 创建吸气剂 function

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

单元测试来测试功能而不是属性

您可以使用 ReflectionClass 访问和操作受保护的变量。

请试试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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