PHPUnit + Laravel单元测试常用技能(3)
测试私有属性可使用ReflectionClass()
, 获取属性用getProperty()
, 设置属性的值用setValue()
, 获取方法用getMethod()
, 设置属性和方法可被访问使用setAccessible(true)
。例如检测白名单路径。
示例代码:
被检测代码:
<?php namespace App\Facades\Services; use App\Exceptions\ExceptionCode; use App\Exceptions\UserException; use Illuminate\Support\Facades\Cache; /** * CC攻击防御器 * Class WebDefender */ class WebDefenderService extends BaseService { //路径白名单(正则) private $pathWhiteList = [ //'^auth\/(.*)', ]; private static $request = null; /** * 请求路径是否在白名单中 * * @return bool */ private function checkPathWhiteList() { $path = ltrim(self::$request->getPathInfo(), '/'); if (!$path || !$this->pathWhiteList || !is_array($this->pathWhiteList)) { return false; } foreach ($this->pathWhiteList as $item) { if (preg_match("/$item/", $path)) { return true; } } return false; } }
检测方法:
<?php namespace Tests\Unit; use App\Facades\Services\WebDefenderService; use Illuminate\Http\Request; use Tests\TestCase; class WebDefenderTest extends TestCase { /** * 检测白名单路径 * @dataProvider additionProviderPathWhiteList * * @param $pathProperty * @param $request * @param $result * * @throws \ReflectionException */ public function testCheckPathWhiteList($pathProperty, $request, $result) { $reflectedClass = new \ReflectionClass('App\Facades\Services\WebDefenderService'); $webDefenderService = new WebDefenderService(); $reflectedPathWhiteList = $reflectedClass->getProperty('pathWhiteList'); $reflectedPathWhiteList->setAccessible(true); $reflectedPathWhiteList->setValue($webDefenderService, $pathProperty); $reflectedRequest = $reflectedClass->getProperty('request'); $reflectedRequest->setAccessible(true); $reflectedRequest->setValue($request); $reflectedMethod = $reflectedClass->getMethod('checkPathWhiteList'); $reflectedMethod->setAccessible(true); $this->assertEquals($result, $reflectedMethod->invoke($webDefenderService)); } public function additionProviderPathWhiteList() { $allPath = ['.*']; $checkPath = ['^auth\/(.*)']; $authSendSmsRequest = new Request([], [], [], [], [], ['HTTP_HOST' => 'api.dev.com', 'REQUEST_URI' => '/auth/sendSms']); $indexRequest = new Request([], [], [], [], [], ['HTTP_HOST' => 'api.dev.com', 'REQUEST_URI' => '/']); $noMatchRequest = new Request([], [], [], [], [], ['HTTP_HOST' => 'api.dev.com', 'REQUEST_URI' => '/product/sendSms']); return [ 'index' => [[], $authSendSmsRequest, false], 'no request' => [$allPath, $indexRequest, false], 'all request' => [$allPath, $authSendSmsRequest, true], 'check auth sms' => [$checkPath, $authSendSmsRequest, true], 'check path no match' => [$checkPath, $noMatchRequest, false] ]; } }
内容版权声明:除非注明,否则皆为本站原创文章。