如何在撰寫測驗時訪問受保護物件 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' => '[email protected]',
'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
uj5u.com熱心網友回復:
您可以使用 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');
uj5u.com熱心網友回復:
為 $data 創建 getter 函式
public function get_data(){
return $this->data;
}
單元測驗測驗功能而不是屬性
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/533696.html
