<?php
namespace Tests;
use PHPUnit\Framework\TestCase;
// 受測範例
class User
{
protected static function getPhone($name)
{
return "{$name}: 09123456789";
}
private function search($id, $name)
{
return "{$id} - {$name}";
}
}
// 測試 User 類別
class MyTest extends TestCase
{
// 測試靜態保護的方法
public function testProtectedStaticMethod()
{
// 直接反射方法
$reflectionMethod = new \ReflectionMethod(User::class, 'getPhone');
$reflectionMethod->setAccessible(true);
// 代入該方法的參數
$result = $reflectionMethod->invoke(new User(), "Cary");
$this->assertEquals("Cary: 09123456789", $result);
}
// 測試私有方法
public function testPrivateMethod()
{
// 直接反射方法
$reflectionMethod = new \ReflectionMethod(User::class, 'search');
$reflectionMethod->setAccessible(true);
// 代入該方法的參數
$result = $reflectionMethod->invoke(new User(), "500800", "Cary");
$this->assertEquals("500800 - Cary", $result);
}
// 混和測試
public function testMix()
{
// 只反射類別
$reflectionClass = new \ReflectionClass(User::class);
// 從反射的類別下去取得靜態方法
$method = $reflectionClass->getMethod('getPhone');
$method->setAccessible(true);
// 為該方法帶入參數
$invoke = $method->invoke(new User(), 'Cary');
// 從反射的類別下去取得方法
$method = $reflectionClass->getMethod('search');
$method->setAccessible(true);
// 為該方法帶入參數
$invoke = $method->invoke(new User(), '500800', 'Cary');
}
}