💻
【PHPUnit】privateメソッドのテスト方法(Unitテスト)
privateメソッドのテストをする方法
TestCase.php
tests/TestCase.php
<?php
namespace Tests;
use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
abstract class TestCase extentds BaseTestCase
{
use CreatesApplications;
}
privateメソッドテストクラス
tests/Unit/(作成したフォルダ/)作成したテストクラス.php
<?php
namespace Tests\Unit;
use Tests\TestCase;
use ReflectionClass;
class 作成したテストクラス extends TestCase
{
private $reflection;
private $private_method_class; // メソッドがあるクラスを格納する変数
protected function setUp() : void
{
parent::setUp();
$this->refreshApplication(); // const.phpなどを使用したい場合は入れる
$private_method_class = new privateMethodClass();
$this->reflection = new ReflectionClass($this->private_method_class);
}
/**
* @param mixed ...$args privateメソッドに使用されている引数
*/
private function callPrivateMethod(...$args) : 使用するprivateメソッドの戻り値
{
$private_method = $this->reflection->getMethod('privateメソッド名');
$private_method->setAccessible(true);
return $method->invoke($this->private_method_class, ...$args);
}
}
上記コードを作成したら、あとはテストメソッドでcallPrivateMethodを呼び出す。
関連記事
Unitテスト作成コマンド
Discussion