Laravel测试中如何访问PHP受保护对象的属性?
在Laravel测试中访问受保护的JsonResponse属性的解决方法
问题说明
编写Laravel测试时,尝试直接访问Illuminate\Http\JsonResponse对象的受保护属性$data时触发权限错误,尽管dd()能显示该属性内容,但直接访问不被允许。
相关代码
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); } }
测试用例(PatientsControllerTest.php)
<?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
解决方法
方法1:使用getContent()解析响应
JsonResponse内置getContent()方法获取原始JSON字符串,再通过json_decode()转换为可操作的数组或对象:
public function testPatientFetch() { $auth_user = $this->getAuthUser(); // 第二个参数为true返回数组,false返回stdClass对象 $responseData = json_decode($auth_user->getContent(), true); dd($responseData); }
方法2:使用测试响应的json()方法
Laravel测试响应对象提供了json()方法,可直接返回解析后的数组格式响应数据,这是最推荐的方式:
public function testPatientFetch() { $auth_user = $this->getAuthUser(); $responseData = $auth_user->json(); dd($responseData); }
方法3:反射机制访问受保护属性(不推荐)
如果必须直接访问受保护属性,可通过PHP反射绕过封装,但这种方式破坏了类的封装性,框架更新可能导致代码失效,仅作为应急方案:
public function testPatientFetch() { $auth_user = $this->getAuthUser(); $reflection = new \ReflectionClass($auth_user); $dataProperty = $reflection->getProperty('data'); $dataProperty->setAccessible(true); $responseData = $dataProperty->getValue($auth_user); dd($responseData); }
内容的提问来源于stack exchange,提问作者Denis Mulindwa
相关产品推荐
相关产品推荐

